gpt4 book ai didi

python-3.x - Python中的颜色检测和比较

转载 作者:行者123 更新时间:2023-12-02 17:28:02 25 4
gpt4 key购买 nike

我试图弄清楚图像中是否存在特定颜色?我想编写一个Python代码,将给定的颜色值与来自图像某些位置坐标的颜色进行比较。我已经尝试过在色彩空间上进行图像分割的解决方案,但是我做不到。

我正在使用Python“OpenCV”。

I want to make program like:

given_color = Blue (Color Values)
if Blue == Color_values_detected_from_image:
print("Blue Color is present at your given area")
else:
print("Given Color Not Found")

您能给我建议从哪里开始吗?

我期望如果我在图像的特定区域给出矩形的坐标,则应将其与我给定的颜色值进行比较。

最佳答案

这可以通过简单的逐像素比较和NumPy的 all 方法来完成。

让我们看下面的代码:

import cv2
import numpy as np

# Read input image
img = cv2.imread('images/colors.png', cv2.IMREAD_COLOR)
cv2.imshow('img', img)

# Region of interest (x1, x2, y1, y2)
roi = (200, 700, 0, 100)
imgRoi = img[roi[2]:roi[3], roi[0]:roi[1]]
cv2.imshow('imgRoi', imgRoi)

# Color of interest [B, G, R]
coi = [0, 255, 0]

# Compare each pixel with color; logical AND over all colors (axis=2)
cmp = np.all(imgRoi == coi, axis=2)

# From here, do whatever you like with this information...

# For example, show mask where color of interest was found
out = np.zeros((imgRoi.shape[0], imgRoi.shape[1], 1), np.uint8)
out[cmp] = 255
cv2.imshow('out', out)

cv2.waitKey(0)

输入图像如下所示:

Input

感兴趣区域(ROI)如下所示:

ROI

作为示例输出,以下是发现感兴趣的颜色 #00ff00的蒙版:

Mask

希望有帮助!

附言Python / NumPy大师可能会建议一种更优雅的方法,将“ (x1, y1)”,“ (x2, y2)”这两个点“翻译”为索引 x1:x2y1:y2。现在,这个符号看起来很麻烦。

关于python-3.x - Python中的颜色检测和比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57900880/

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