在官网下载了OpenCV4.5.3版本,Python3.6。
使用import cv2,编译时提示
于是我在cmd中输入python -m pip install matplotlib进行下载(pip install numpy应该也可以)
经过漫长的等待,下载完成后,再编译,成功调用了OpenCV!
Python+OpenCV实现人脸检测源代码:
import cv2
cap = cv2.VideoCapture(0)
#打开电脑自带摄像头
while(True):
# Capture frame-by-frame,逐帧捕获画面
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
xmlfile = r'E:\opencv\sources\data\haarcascades_cuda\haarcascade_frontalface_default.xml'
#这里改成你的haarcascade_frontalface_default.xml文件的路径
face_cascade = cv2.CascadeClassifier(xmlfile)
faces = face_cascade.detectMultiScale(
gray,
scaleFactor=1.15,
minNeighbors=5,
minSize=(5, 5),
)
print("发现{0}个目标!".format(len(faces)))
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + w), (0, 255, 0), 2)
cv2.imshow("frame", frame)
# Display the resulting frame
if cv2.waitKey(1) & 0xFF == ord('q'):
break #输入q后退出循环
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
运行结果:
如果还没解决无法import cv2的问题,检查一下电脑系统环境变量是否添加!
修改完环境变量之后重启visual studio再试试。