如何获得图像中特定直线的RGB值?

时间:2019-09-20 15:57:53

标签: python opencv image-processing

这是一幅图像,其中有两条红色(无论颜色如何)的线条。我想检测该行,然后获取该行的rgb值。如何通过使用OpenV或任何其他python库来做到这一点。

enter image description here

我尝试了这种代码,其中打印了许多值的列表:

import cv2

img = cv2.imread('C:/Users/Rizwan/Desktop/result.jpg')

print(img)

1 个答案:

答案 0 :(得分:1)

一种可能性是转到HSV colourspace并寻找红色调。红色很难找到,因为它们在“色相/饱和度/值”轮上跨过0和360度,因此我将反转图像并寻找青色,即在反转图像中红色出现的地方。

#!/usr/bin/env python3

import numpy as np
import cv2

# Load the image as BGR
im = cv2.imread('strip.jpg')

# Invert image, i.e. 255-im, to make reds into cyan and convert to HSV
hsv = cv2.cvtColor(255-im, cv2.COLOR_BGR2HSV) 

# Set low and high limit for the tones we want to identify - based on Hue of cyan=90 in OpenCV 
lo = np.uint8([80,30,0])
hi = np.uint8([95,255,255]) 

# Mask all red pixels
mask = cv2.inRange(hsv,lo,hi)

# Save mask for fun
cv2.imwrite('result1.png',mask)

这给出了这一点:

enter image description here

继续使用代码,我们现在将该蒙版应用于原始图像以使无趣的像素变黑:

# Zero out to black all uninteresting pixels in original image
im[mask<255] = 0
cv2.imwrite('result2.png',im)

enter image description here

# Reshape as a tall column of R, G, B values and find unique rows, i.e. unique colours
unique = np.unique(im.reshape(-1,3), axis=0)
print(unique)

大约有700个RGB三胞胎。继续,抓住独特的颜色并写入图像,以便我们可以看到它们:

# This line is a hack based solely on the current image just for illustration
cv2.imwrite('unique.png',unique[:625,:].reshape((25,25,3)))

enter image description here