gpt4 book ai didi

python - 检测到特定颜色后停止网络摄像头

转载 作者:太空宇宙 更新时间:2023-11-03 23:17:40 24 4
gpt4 key购买 nike

我写了一个检测淡粉色的代码。现在我想添加一个代码,它会在检测到浅粉色后自动关闭网络摄像头。你能帮我解决这个问题吗?这是EDITED代码:

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while(1):
_, frame = cap.read()

hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

lower_pink = np.array([160,50,50])
upper_pink = np.array([180,255,255])

mask = cv2.inRange(hsv, lower_pink, upper_pink)

# Bitwise-AND mask and original image
res = cv2.bitwise_and(frame,frame, mask= mask)
cv2.imshow('frame',frame)
cv2.imshow('mask',mask)
cv2.imshow('res',res)
break

if(cv2.countNonZero(mask) > 0):
print("FOUND")
raise SystemExit

cv2.destroyAllWindows()

最佳答案

带有无条件 break(并且没有可能的 continue)的循环没有意义,因为它在语义上不是循环。

测试必须在循环内进行,因为您希望将它应用于每张捕获的图像,直到您找到第一张包含足够粉红色的图像。然后 break 循环。不要在这里退出程序,因为这样循环后的清理代码就不会再执行了。通过引发 SystemExit 退出无论如何有点奇怪,这就是 sys.exit() 函数的目的。

import cv2
import numpy as np

def main():
lower_pink = np.array([160, 50, 50])
upper_pink = np.array([180, 255, 255])
threshold = 100 # TODO Adapt to your needs.
cap = cv2.VideoCapture(0)

while True:
_, frame = cap.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, lower_pink, upper_pink)
masked = cv2.bitwise_and(frame, frame, mask=mask)
cv2.imshow('frame', frame)
cv2.imshow('mask', mask)
cv2.imshow('masked', masked)
# if cv2.countNonZero(mask) > threshold:
# print('FOUND')
# break
print(cv2.countNonZero(mask))
#
# Wait for escape key.
#
if cv2.waitKey(500) == 27:
break

cv2.destroyAllWindows()


if __name__ == '__main__':
main()

实际的阈值测试被注释掉并替换为打印掩码的像素数,因此您可以确定哪个值适合您的需要。

关于python - 检测到特定颜色后停止网络摄像头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36618636/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com