参考这篇文章的代码时,遇到了错误,仔细研究后发现,是由于我本机安装的opencv版本与参考代码所使用的不同造成的。我用的opencv版本是3.4.2,参考代码的版本不太清楚。
下面把调试完可以编译的代码贴上:
import cv2
import numpy as np
import imutils
def show_webcam(mirror=False):
cam = cv2.VideoCapture(0)
flag=1
while True:
ret_val, img=cam.read()
text = "Unoccpied"
if img is None:
break
cv2.imshow('webcam', img)
img_resized =imutils.resize(img,width=500)
cv2.imshow("resized",img_resized)
gray = cv2.cvtColor(img_resized,cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (21,21),0)
cv2.imshow("gaussblur",gray)
if flag:
cv2.namedWindow('firstframe', cv2.WINDOW_AUTOSIZE)
flag = 0
image_resized=imutils.resize(img,width=500)
print("image_resized.shape=%d",image_resized.shape)
firstframe = gray
cv2.imshow('firstframe',firstframe)
print("firstframe.shape=%d",firstframe.shape)
framedelta=cv2.absdiff(firstframe,gray)
cv2.imshow("framedelta",framedelta)
thresh = cv2.threshold(framedelta,100,255,cv2.THRESH_BINARY)[1]
thresh = cv2.dilate(thresh,None,iterations=2)
cnts = cv2.findContours(thresh.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
for c in cnts:
# if cv2.contourArea(c)< args["min_area"]
# continue
(x, y, w, h) = cv2.boundingRect(c)
cv2.rectangle(img_resized, (x, y), (x+w, y+h),(0,255,0),2)
text = "Occpied"
cv2.putText(img_resized, "Room Status : {}".format(text),(10,20),
cv2.FONT_HERSHEY_SIMPLEX,0.5, (0,0,255),2)
cv2.imshow("Thresh",thresh)
cv2.imshow("Frame",img_resized)
if cv2.waitKey(1) == 27:
break
cv2.destroyAllWindows()
cam.release()
def main():
print(cv2.__version__)
show_webcam(mirror=True)
if __name__ == '__main__':
main()
好像print的使用还有些问题,先保存一下吧,稍后再改