Steven97102
Steven97102

Reputation: 344

OpenCV get pixels on an circle

I'm new to OpenCV and I'm trying to get the pixels of a circle from an image.

For example, I draw a circle on a random image:

import cv2

raw_img = cv2.imread('sample_picture.png')
x = 50
y = 50
rad = 20
cv2.circle(raw_img,(x,y),rad,(0,255,0),-1)
cv2.imshow('output', raw_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

The output shows an image with a circle. However, I want to be able to get all the pixel on the circle back in the form of an array. Is there any way to do this? I know I can get the approximate coordinates from the circle formula, but it will involve a lot of decimal calculations, and I'm pretty sure that the function cv2.circle() has already calculated the pixel, so is there a way to get it out from the function itself instead of calculating my self?

Also, if it is possible I would like to get the pixel of an ellipse using cv2.ellipse() back as an array of coordinates. But this time, I want to get the pixel only from a part of an ellipse (from a certain angle to another angle, which I can specify in the parameter of cv2.ellipse()).

Thank you.

Upvotes: 6

Views: 6015

Answers (1)

yapws87
yapws87

Reputation: 1839

You can achieve what you are looking for by using the numpy function:

numpy.where(condition[, x, y])

Detailed explanation of function in link :https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.where.html

In your case, you would want to it to return the coordinates that has non-zero values. Using this method, you can draw anything on an empty array and it will return all rows and columns corresponding to non-zeros.

It will return the index of the array that satisfies the condition you set. Below is a code showing an example of the usage.

import cv2
import numpy as np

raw_img = cv2.imread('sample_picture.png')
x = 50
y = 50
rad = 20
cv2.circle(raw_img,(x,y),rad,(0,255,0),-1)

# Here is where you can obtain the coordinate you are looking for
combined = raw_img[:,:,0] + raw_img[:,:,1] + raw_img[:,:,2]
rows, cols, channel = np.where(combined > 0)    

cv2.imshow('output', raw_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Upvotes: 2

Related Questions