简体   繁体   English

Python 和 PiCamera 颜色检测布尔问题

[英]Python and PiCamera Color Detection Boolean Issues

I'm fairly new with Python and trying to code a way a PiCamera to pick up on different colors and react based off of that.我对 Python 相当陌生,并试图编写一种让 PiCamera 拾取不同颜色并基于此做出反应的方式。 My current attempt for each color is to take a picture and detect the color involved.我目前对每种颜色的尝试是拍照并检测所涉及的颜色。 Some example code is below.一些示例代码如下。

def red_detect():
    # initialize the camera and grab a reference to the raw camera capture
    rawCapture = PiRGBArray(camera, size=(640, 480))

    # allow the camera to warmup
    time.sleep(0.1)

    # grab an image from the camera
    camera.capture(rawCapture, format="bgr")
    image = rawCapture.array

    # Convert BGR to HSV
    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

    lower_red = np.array([161, 155, 84],np.uint8)
    upper_red = np.array([179, 255, 255],np.uint8)
    red_mask = cv2.inRange(hsv, lower_red, upper_red)
    red = cv2.bitwise_and(image, image, mask=red_mask)

    return 255 in cv2.inRange(hsv, lower_red, upper_red)  

and then that code will be evaluated with an if statement such as if green == True:然后将使用 if 语句评估该代码,例如if green == True:

However, all of my colors are coming back as True.然而,我所有的颜色都恢复原样了。 Am I approaching taking a picture wrong?我接近拍照错误吗?

If you just wanna detect the color of image, there are easier method to do:如果您只想检测图像的颜色,可以使用更简单的方法:

from PIL import Image

image = Image.open('image.jpg')

w, h = image.size

pixel = []

for x in range(w):
    for y in range(h):
        r, g, b = image.getpixel((x, y))
        pixel.append([r, g, b])

avr = [sum(x)//len(x) for x in zip(*pixel)]

colors = dict(zip(['red','green','blue'],[i for i in avr]))
print(max(colors))

PS I use pillow module there. PS我在那里使用枕头模块。 Helped than I could, also new to python比我能帮上忙,也是python的新手

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM