提问者:小点点

opencv中需要整数参数int-get-float


我已经在下面显示了代码,但是当我尝试执行它时,得到

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

我不确定问题出在哪里,在mineConclosingCircle中,值已转换为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()`

共3个答案

匿名用户

这个答案可能太迟了,但我发现cv2.circle只能接受中心坐标精度高达Float32。如果坐标在flat64中,它将抛出此错误。简单的解决方法是始终将中心坐标转换为numpy.float32。

匿名用户

我对您的代码做了一些小的修改,以将浮点数转换为整数。它现在运行没有错误。检查这个:

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)
    x = np.round(x).astype("int")
    y = np.round(y).astype("int")
    center = (x,y)
    radius = np.round(radius).astype("int")
    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()

匿名用户

修改你的代码如下你不需要使用返回值的cv2.circle.

cv2.circle(img,center, radius, (0,255, 0), 2)