1、捕获摄像头和实时显示
import cv2
import numpy as np
import pickle
import matplotlib.pyplot as plt
cap = cv2.VideoCapture(0)
while True:
ret,frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
1.1Sobel进行边缘检测
加入想对摄像头捕获的图片进行加工处理,则对每一个图片处理即可
import cv2
import numpy as np
import pickle
import matplotlib.pyplot as plt
def sobel_pocessed(img):
# Sobel边缘检测算子
x = cv2.Sobel(img, cv2.CV_16S, 1, 0)
y = cv2.Sobel(img, cv2.CV_16S, 0, 1)
# cv2.convertScaleAbs(src[, dst[, alpha[, beta]]])
Scale_absX = cv2.convertScaleAbs(x) # convert 转换 scale 缩放
Scale_absY = cv2.convertScaleAbs(y)
result = cv2.addWeighted(Scale_absX, 0.5, Scale_absY, 0.5, 0)
return result
cap = cv2.VideoCapture(0)
while True:
ret,frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#result=gray
result=sobel_pocessed(frame)
# Display the resulting frame
cv2.imshow('liuyunshengsir_opencv',result)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
2、从摄像头内抓拍图片
import cv2
import numpy as np
import pickle
import matplotlib.pyplot as plt
cap = cv2.VideoCapture(0)
index = 0
while True:
ret,frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('p'):
cv2.imwrite("kk.jpg",frame)
index = index + 1
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()