Ask Your Question
0

Find first non-black pixel

asked 2020-07-24 03:08:04 -0600

Cornelius gravatar image

I have a very simple input image: it's fully black and has a tiny bright red dot somewehere in it. The colors are "pure", meaning the blacks are (0,0,0), the red dot is at full 255 red intensity.

Now I would like to find the coordinate of the red dot. I thought this would be rather simple, since all I need is the position of the first non-black pixel in my image. That would be good enough for my application.

But I have searched quite a while and could not find a simple and fast solution to do this with OpenCV.

PS: I know that OpenCV has a blob detection, but that seems waaay to powerful (and expensive) for this simple task.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
0

answered 2020-07-24 03:19:38 -0600

berak gravatar image

updated 2020-07-24 03:48:27 -0600

probably, findNonZero() might help, like:

red_channel = img[:,:,0]
points = cv2.findNonZero(red_channel) # x,y order
edit flag offensive delete link more

Comments

1

That sounds like a good solution. I'm having some trouble using this function though. This is my code:

coords = cv.findNonZero(red_channel) # x,y

debug = cv.circle(debug, (coords[0].x, coords[0].y), 3, (255, 0, 0), 3)

cv.imshow('debug', debug)

gives me the following error:

AttributeError: 'numpy.ndarray' object has no attribute 'x'

Cornelius gravatar imageCornelius ( 2020-07-24 03:46:16 -0600 )edit

yea sorry for being unclear, x,y is the order, not the access. example:

>>> a = np.array([[0,0,0],[0,0,1],[0,0,0]])
>>> cv2.findNonZero(a)
array([[[2, 1]]], dtype=int32)

so, x=points[0][0][0], and y=points[0][0][1]

(the extra, 3rd dimension is due to the (weird) way std::vector gets translated to numpy arrays)

berak gravatar imageberak ( 2020-07-24 03:52:05 -0600 )edit
1

Thank you for the clarification. That is indees rather inintuitive ;-)

Cornelius gravatar imageCornelius ( 2020-07-24 03:58:22 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2020-07-24 03:08:04 -0600

Seen: 2,358 times

Last updated: Jul 24 '20