检测图像中间的颜色(OpenCV,Python)

时间:2018-05-04 15:19:58

标签: python opencv color-picker roi

我有这3张图片(考虑"图片"整个广场不仅仅是里面的图 - 这只是为了演示目的):

im1 im2 im3

我想要做的是检测每个中间(中间)的颜色。因此,在中心有一个区域(正方形或圆形),OpenCV检测哪个是颜色。 有点像颜色选择器...

目的是拥有3个值,每个图像3个(BGR)。

示例:

im4

投资回报率的颜色是什么?

由于

修改

使用此代码,我可以找到图像的中间并应用蒙版。

import cv2
import numpy as np

img = cv2.imread("im2.png")

height, width, depth = img.shape
circle_img = np.zeros((height, width), np.uint8)

mask = cv2.circle(circle_img, (int(width / 2), int(height / 2)), 20, 1, thickness=-1)
masked_img = cv2.bitwise_and(img, img, mask=circle_img)

cv2.imshow("masked", masked_img)
cv2.waitKey(0)

现在仍然可以找到蒙面区域的BGR(可见一个......)

5 个答案:

答案 0 :(得分:2)

import cv2
import numpy as np

img = cv2.imread('image.png')
height, width = img.shape[:2]
# Change these values to fit the size of your region of interest
roi_size = 10 # (10x10)
roi_values = img[(height-roi_size)/2:(height+roi_size)/2,(width-roi_size)/2:(width+roi_size)/2]
mean_blue = np.mean(roi_values[:,:,0])
mean_green = np.mean(roi_values[:,:,1])
mean_red = np.mean(roi_values[:,:,2])

print("R: {}  G: {}  B: {}").format(mean_red, mean_green, mean_blue)  

答案 1 :(得分:1)

确保图像为PhotoImage,计算中间点并获取颜色:

r,g,b = image.get(x, y)

答案 2 :(得分:1)

使用枕头:

from PIL import Image

im = Image.open(path_to_image)

width, height = im.size #get image size

#since you do not specify the size of the center area in the question, just replace the below variables with what you want
left = (width - your_width)/2
top = (height - your_height)/2
right = (width + your_width)/2
bottom = (height + your_height)/2

im.crop((left, top, right, bottom)) #crop the center of the image

rgb = im.convert('RGB') # get three R G B values
r, g, b = rgb.getpixel((1, 1))

print(r,g,b)

使用OpenCV将第一行替换为:

im = cv2.imread(path_to_image)
height, width = im.shape[:2]

答案 3 :(得分:0)

你有一张尺寸为x x h的图像。设想假设每边11像素的roi大小,因此offset = 5

从(w / 2 - width / 2,h / 2 - height / 2)到(w / 2 + width / 2,h / 2 + height / 2)访问像素。

然后计算所有提取像素的平均值(这样你就可以更好地适应颜色变化)。

如果您希望在其他空间颜色中根据要分析的图片类型,您可以更改颜色空间。

答案 4 :(得分:0)

这将使用OpenCV找到图像中心的像素的RGB值。

import cv2
import numpy as np

img = cv2.imread("image.png")

height, width, depth = img.shape
circle_img = np.zeros((height, width), np.uint8)

mask = cv2.circle(circle_img, (int(width / 2), int(height / 2)), 1, 1, thickness=-1)
masked_img = cv2.bitwise_and(img, img, mask=circle_img)

circle_locations = mask == 1
bgr = img[circle_locations]

rgb = bgr[..., ::-1]

print(rgb)

Source

相关问题