Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Open CV2 Color Detection Mask to Pixel Coordinates

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.

Output of my color detection

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.

like image 695
Joshua Jenkins Avatar asked Apr 21 '26 13:04

Joshua Jenkins


1 Answers

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.
like image 118
Soltius Avatar answered Apr 24 '26 02:04

Soltius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!