我已经显示了下面的代码,但是当我尝试执行它时,得到
Traceback (most recent call last):
File "/home/decentmakeover2/Code/cv.py", line 22, in <module>
img = cv2.circle(img,center, radius, (0,255, 0), 2)
TypeError: integer argument expected, got float
Run Code Online (Sandbox Code Playgroud)
我不确定问题是什么,minEnclosingCircle值已转换为int,但我仍然遇到相同的错误,关于可能是什么问题的任何想法?
import numpy as np
import cv2
import os
from scipy import ndimage
img = cv2.pyrDown(cv2.imread('img.jpeg'))
ret, thresh = cv2.threshold(cv2.cvtColor(img.copy(), cv2.COLOR_BGR2GRAY), 127, 255, cv2.THRESH_BINARY)
image, contours, heir = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
x, y , w, h = cv2.boundingRect(c)
cv2.rectangle(img, (x,y), (x+w, y+h), (0, 255, 0), 2)
rect = cv2.minAreaRect(c)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img, [box], 0 , (0, 0, 255), 3)
(x,y), radius = cv2.minEnclosingCircle(c)
center = (int(x), int(y))
radius = int(radius)
img = cv2.circle(img, center, radius, (0,255, 0), 2)
cv2.drawContours(img, contours, -1, (255, 0, 0), 1)
cv2.imshow('contours',img)
cv2.waitKey(0)
cv2.destroyAllWindows()`
Run Code Online (Sandbox Code Playgroud)
小智 8
这个答案可能为时已晚,但我发现 cv2.circle 只能接受高达 float32 的中心坐标精度。如果坐标在 float64 中,则会抛出此错误。简单的解决方案总是将中心坐标转换为 numpy.float32。
如下修改代码,您不需要使用 cv2.circle 的返回值。
cv2.circle(img,center, radius, (0,255, 0), 2)
Run Code Online (Sandbox Code Playgroud)