Python Open CV2 Color Detection Mask to Pixel Coordinates

柔情痞子 提交于 2019-12-06 13:33:38
Soltius

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!