OpenCV在一个圆圈上获取像素 [英] OpenCV get pixels on an circle
问题描述
我是OpenCV的新手,我正在尝试从图像中获取圆的像素.
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()
输出显示带圆圈的图像. 但是,我希望能够以数组的形式返回圆上的所有像素.有什么办法吗?我知道我可以从圆公式中获得近似坐标,但是它将涉及很多十进制计算,而且我很确定函数 cv2.circle() >已经计算了像素,是否有办法从函数本身中获取像素,而不是计算自己的像素?
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?
此外,如果可能的话,我想使用 cv2.ellipse() 作为坐标数组来获取椭圆的像素.但是这一次,我只想从椭圆的一部分(从某个角度到另一个角度,可以在cv2.ellipse()的参数中指定)获取像素.
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()).
谢谢.
推荐答案
您可以使用numpy函数实现所需的功能:
You can achieve what you are looking for by using the numpy function:
numpy.where(condition[, x, y])
链接中功能的详细说明: https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.where.html
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()
这篇关于OpenCV在一个圆圈上获取像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!