1. Access the USB camera
Plug in the usb camera, enter lsusb in command line mode
If you see a camera in the listed information, it means that the recognition is successful and can be used.
2. Test camera
Installfswebcam
sudo apt-get install fswebcam
Enter the following command to turn on the camera
fswebcam --no-banner -r 640x480 image3.jpg
Installluvcview
sudo apt-get install luvcview
Enter the following command to turn on the camera
luvcview -s 640x480
3. Install python2
sudo apt-get install python
If you find that python3 is installed, you need to change python to python2
4. Install OpenCV
Run the following two commands separately~
sudo apt-get install libopencv-dev
sudo apt-get install python-opencv
Enter the command in the command line mode to test whether the installation is successful (if the python command does not exist, it means that there may be python2 and 3 environments at the same time, and you need to specify python2)
python
import cv2
cv2.__version__
If the version number shown in the figure below appears normally, it means the installation is successful!
Finally exit the python environment, you can enter exit()
, or direct shortcut keysctrl+D
5. Photo storage function code
The image preprocessing part is changed as needed.
import cv2
import numpy as np
name = 0
cap = cv2.VideoCapture(0)
cap.set(3,640)
cap.set(4,480)
ret, frame = cap.read()
rows, cols, channels = frame.shape
print(cols, rows, channels)
# 图像预处理
def img_p(img):
# 灰度化
gray_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 平滑滤波
blur = cv2.blur(gray_img, (3,3))
# 二值化
ret1, th1 = cv2.threshold(blur, 190, 255, cv2.THRESH_BINARY)
# 透视变换
b = 50
pts1 = np.float32([[b, 0], [cols-b, 0], [0, rows], [cols, rows]])
pts2 = np.float32([[0, 0], [cols, 0], [0, rows], [cols, rows]])
M = cv2.getPerspectiveTransform(pts1, pts2)
dst = cv2.warpPerspective(blur, M, (cols, rows))
return dst
while(1):
ret,frame = cap.read()
dst = img_p(frame)
cv2.imshow('usb camera', dst)
k = cv2.waitKey(1)
if (k == ord('q')):
break
elif(k == ord('s')):
#name = input('name:')
name += 1
#filename = r'./camera/' + str(name) + '.jpg'
filename = str(name) + '.jpg'
cv2.imwrite(filename, dst)
print(filename)
#break
cap.release()
cv2.destroyAllWindows()
Then the terminal executes python 文件名.py
, and you can see the screen
(If you are prompted that the command python does not exist, it means that python2 and 3 environments may exist at the same time, and you need to specify python2)
python 文件名.py
Note: If the following errors or errors related to connection timeout occur after the terminal is executed
, change the usb port of the camera, and try all the four ports of the Raspberry Pi , and it will be usable.
Put the USB CAMERA interface at the front, press s to save the picture, q to exit the program.
OK.
6. Error: python Non-ASCII character '\xe5' in file
Add at the beginning of the script
# coding=UTF-8
That's it.