I am currently working in Python to do color detection on a single image. After loading my image and establishing my RGB (or BGR in CV2), I use the following 2 lines to produce a mask and a output image.
mask = cv2.inRange(image, lower, upper)
output = cv2.bitwise_and(image, image, mask = mask)
Then the code displays the following image.
But now, I would like to take the processed image and extract pixel coordinate points for the green line.
Thanks. Any help would be appreciated.
So, how about findNonZeros() on a binarised version of your image ? Starting with the image with the green line on black background :
import cv2
import numpy as np
img = cv2.imread(output.png)
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #converting to grayscale
img = img.astype(np.uint8)
#get all non zero values
coord = cv2.findNonZero(img)
EDIT : It has been pointed out on another question that you can also use numpy's function nonzeros. It gives the same results, but I find it to be slower
import cv2
import numpy as np
import time
so=cv2.imread(your_image,0)
start1=time.clock()
coord=cv2.findNonZero(so)
end1=time.clock()
start2=time.clock()
coord2=np.nonzero(so)
end2=time.clock()
print("cv2.findNonZeros() takes "+str(end1-start1)+" seconds.")
print("np.nonzero() takes "+str(end2-start2)+" seconds.")
>>> cv2.findNonZeros() takes 0.003266 seconds.
>>> np.nonzero() takes 0.021132 seconds.
My solution is not so neat but you can refine it later.
I drew a line across a black image:
And I have obtained the coordinate values of those pixels in white. I have taken two arrays to store them.
Code:
listi = [] #---stores coordinate corresponding to height of the image
listj = [] #---stores coordinate corresponding to width of the image
for i in range(0, mask.shape[0]):
for j in range(0, mask.shape[1]):
if(mask[i, j] == 255):
listi = np.append(listi, i)
listj = np.append(listj, j)
I know there is a much better way out there. I will update this answer once I figure it out.
来源:https://stackoverflow.com/questions/41837005/python-open-cv2-color-detection-mask-to-pixel-coordinates