Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

python - How can i get the RGB value of specific straight line in the image?

This is an image which there are two red(whatever color) lines. I want to detect the line and then want to get the rgb values of that line. How can I do this by using OpenV or any other library of python.

enter image description here

I tried this kind of code which print a list of many values:

import cv2

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

print(img)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One possibility is to go to HSV colourspace and look for red tones. Reds are harder to find because they straddle 0 and 360 degrees on the Hue/Saturation/Value wheel so I will invert the image and look for cyan which is where red will show up in an inverted image.

#!/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)

That gives this:

enter image description here

Carrying on with the code, we now apply that mask to the original image to blacken uninteresting pixels:

# 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)

That gives around 700 RGB triplets. Carrying on, grab the unique colours and write to an image so we can see them:

# 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...