代码:
import cv2
import cv2 as cv
import time
from skimage import transform, img_as_float
import numpy as np
import dlib
color = ('b','g','r')
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
cap.set(cv.CAP_PROP_FRAME_WIDTH, 650)
cap.set(cv.CAP_PROP_FRAME_HEIGHT, 500)
detector = dlib.get_frontal_face_detector()
near_threshold = 0.01
fps = int(cap.get(cv2.CAP_PROP_FPS))
print("This is the fps ", fps)
img = cv2.imread("image.png", cv2.IMREAD_UNCHANGED)
img = transform.resize(img, (290, 290))
img = img_as_float(img)
if (img.shape[2] < 4):
print('sorry can\'t mask')
while cap.isOpened():
ret, frame = cap.read()
face_rects, scores, idx = detector.run(frame, 0)
if ret == True:
frame = img_as_float(frame)
frame[100:390, 0:290, 0] *= 1 - img[:, :, 3]
frame[100:390, 0:290, 1] *= 1 - img[:, :, 3]
frame[100:390, 0:290, 2] *= 1 - img[:, :, 3]
frame[100:390, 0:290, :] += img[:, :, :3]
for i, d in enumerate(face_rects):
x1 = d.left()
y1 = d.top()
x2 = d.right()
y2 = d.bottom()
faceLong = y2 - y1
upface = frame[y1:y1 + int(1 / 3 * faceLong), x1:x2]
downface = frame[y1 + int(1 / 3 * faceLong):y2, x1:x2]
hist1 = cv.calcHist([upface], [0, 1, 2], None, [256, 256, 256], [0, 256, 0, 256, 0, 256])
hist2 = cv.calcHist([downface], [0, 1, 2], None, [256, 256, 256], [0, 256, 0, 256, 0, 256])
cv.normalize(hist1, hist1, 0, 1.0, cv.NORM_MINMAX)
cv.normalize(hist2, hist2, 0, 1.0, cv.NORM_MINMAX)
near = cv.compareHist(hist1, hist2, 0)
if (near < near_threshold):
cv.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 4, cv.LINE_AA)
cv.putText(frame, "Wear Mask", (x1, y1), cv.FONT_HERSHEY_DUPLEX, 0.7, (0, 255, 0), 1, cv.LINE_AA)
else:
cv.rectangle(frame, (x1, y1), (x2, y2), (0, 0, 255), 4, cv.LINE_AA)
cv.putText(frame, "No Mask", (x1, y1), cv.FONT_HERSHEY_DUPLEX, 0.7, (0, 0, 255), 1, cv.LINE_AA)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
错误:
Traceback (most recent call last):
File "C:\Users\user\PycharmProjects\untitled1\測試\PNG+CAM test.py", line 58, in <module>
hist1 = cv.calcHist([upface], [0, 1, 2], None, [256, 256, 256], [0, 256, 0, 256, 0, 256])
cv2.error: OpenCV(4.5.2) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-m8us58q4\opencv\modules\imgproc\src\histogram.cpp:1007: error: (-210:Unsupported format or combination of formats) in function 'cv::calcHist'
我想知道如何解决这个错误,谢谢。:D