1. 利用Opencv,就是代码中的cv2,使用前要导入 即 import
2. opencv的安装,可以在终端 用pip install
或者在pycharm中 文件——设置——项目——解释器——旁边“ + ”,输入opencv-python即可
import cv2
cap = cv2.VideoCapture(0) #调用0摄像头,外接摄像头的话此处为1
faceCascade = cv2.CascadeClassifier('face_detect.xml')
while True:
ret, frame = cap.read()
if ret:
frame = cv2.resize(frame, (0 , 0), fx=0.6, fy=0.6)#原始图像
img = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) #黑白
faceRect =faceCascade.detectMultiScale(img,1.1,4)
print(len(faceRect),frame.shape)
count = str(len(faceRect))
if count != '0':
for (x, y, w, h) in faceRect:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
print(type(x))
print(type(frame.shape))
cv2.putText(frame, 'human', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0, 2))
cv2.putText(frame, 'human:' + count, (10, 280), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255,), 5)
cv2.imshow('pc camera2', frame) # 原始图像
else:
cv2.imshow('pc camera2', frame)
else:
break
if cv2.waitKey(1) == ord('m'):
break