Python OpenCV 椭圆 - 最多接受5个参数(给了8个)
我现在完全搞不懂为什么我在用OpenCV画椭圆的时候遇到问题,查了文档也没找到答案。
首先,我用的是CV 2.4.9版本。
>>> cv2.__version__
'2.4.9'
>>>
其次,我尝试使用以下代码:
>>> help(cv2.ellipse)
Help on built-in function ellipse in module cv2:
ellipse(...)
ellipse(img, center, axes, angle, startAngle, endAngle, color[, thickness[,
lineType[, shift]]]) -> None or ellipse(img, box, color[, thickness[, lineType
]]) -> None
我想画的椭圆看起来是这样的:
cx,cy = 201,113
ax1,ax2 = 37,27
angle = -108
center = (cx,cy)
axes = (ax1,ax2)
cv2.ellipse(frame, center, axes, angle, 0 , 360, (255,0,0), 2)
但是运行这段代码后,结果却是这样的:
>>> cv2.ellipse(frame,center,axes,angle,0,360, (255,0,0), 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ellipse() takes at most 5 arguments (8 given)
>>>
谁能帮帮我?
补充说明:
我想用以下代码作为框架:
cap = cv2.VideoCapture(fileLoc)
frame = cap.read()
显然,可以通过使用以下代码来解决这个问题:
pil_im = Image.fromarray(frame)
cv2.ellipse(frame,center,axes,angle,0,360,(255,0,0), 2)
pil_im = Image.fromarray(raw_image)
pil_im.save('C:/Development/export/foo.jpg', 'JPEG')
5 个回答
0
只需要打印一下输入的参数,看看它们的形状、格式和数据类型是否和OpenCV的文档一致。发现其中一个参数有问题后,这个方法帮我解决了问题。
0
(h, w) = image.shape[:2]
(cX, cY) = (int(w * 0.5), int(h * 0.5))
# divide the image into four rectangles/segments (top-left,
# top-right, bottom-right, bottom-left)
segments = [(0, cX, 0, cY), (cX, w, 0, cY),
(cX, w, cY, h), (0, cX, cY, h)]
# construct an elliptical mask representing the center of the
# image
(axesX, axesY) = (int(w * 0.75) / 2, int(h * 0.75) / 2)
ellipMask = np.zeros(image.shape[:2], dtype="uint8")
cv2.ellipse(ellipMask, (int(cX), int(cY)), (int(axesX), int(axesY)), 0, 0, 360, 255, -1)
对我来说是有效的
1
其实,如果你想从0°画到360°,可以使用浮点数,只需要用一个椭圆参数来调用这个函数:
ellipse_float = ((113.9, 155.7), (23.2, 15.2), 0.0)
cv2.ellipse(image, ellipse_float, (255, 255, 255), -1);
或者你也可以用一行代码来实现:
cv2.ellipse(image, ((113.9, 155.7), (23.2, 15.2), 0.0), (255, 255, 255), -1);
# compared to the following which does not work if not grouping the ellipse paramters in a tuple
#cv2.ellipse(image, (113.9, 155.7), (23.2, 15.2), 0.0, 0, 360, (255, 255, 255), -1); # cryptic error
不过,如果你想要添加起始角度和结束角度的话,这样就不行了。
1
这是我的iPython会话,看起来运行得不错:
In [54]: cv2.__version__
Out[54]: '2.4.9'
In [55]: frame = np.ones((400,400,3))
In [56]: cx,cy = 201,113
In [57]: ax1,ax2 = 37,27
In [58]: angle = -108
In [59]: center = (cx,cy)
In [60]: axes = (ax1,ax2)
In [61]: cv2.ellipse(frame, center, axes, angle, 0 , 360, (255,0,0), 2)
In [62]: plt.imshow(frame)
Out[62]: <matplotlib.image.AxesImage at 0x1134ad8d0>
这个运行成功了,并生成了以下内容:
所以,有点奇怪……也许是你导入cv2
模块的方式有问题?
或者(更有可能的是)你的frame
对象到底是什么类型/结构呢?
37
我遇到过同样的问题,并且解决了。我的第一行无法运行的代码是:
cv2.ellipse(ellipMask, (113.9, 155.7), (23.2, 15.2), 0.0, 0.0, 360.0, (255, 255, 255), -1);
我发现坐标(还有中心点)必须是整数的元组,而不是浮点数。所以下面这一行是可以的!
cv2.ellipse(ellipMask, (113, 155), (23, 15), 0.0, 0.0, 360.0, (255, 255, 255), -1);
我觉得你也应该注意其他值的格式是否正确。
这是来自OpenCV官网的链接: http://answers.opencv.org/question/30778/how-to-draw-ellipse-with-first-python-function/