我试图检测给定图像中的硬币以绘制垂直线或将落在同一直线下的硬币分组。
import cv2
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
img = Image.open("coin.jpg")
imgUMat = np.float32(img)
gray = cv2.cvtColor(imgUMat, cv2.COLOR_BGR2GRAY)
#plt.imshow(img)
#gray = (np.float32(imgUMat), cv2.COLOR_RGB2GRAY)
#gray = cv2.cvtColor(cv2.UMat(img), cv2.COLOR_RGB2GRAY)
#gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
#gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.resize(gray,None,fx=0.25, fy=0.25, interpolation = cv2.INTER_CUBIC)
img = cv2.medianBlur(gray,1)
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20,
param1=30,
param2=15,
minRadius=0,
maxRadius=0)
#circles = cv2.HoughCircles(gray,cv2.HOUGH_GRADIENT,1,100,param1=100,param2=1)
if (circles!=None):
i = np.uint16(np.around(circles))
cv2.circle(gray,(i[0,0,0],i[0,0,1]),i[0,0,2],(255,255,255),1)
cv2.circle(gray,(i[0,0,0],i[0,0,1]),1,(255,255,255),1)
center_x.append(i[0,0,0])
center_y.append(i[0,0,1])
运行代码时,我在circle变量上出现了一个错误,说,
错误:OpenCV(4.1.1)C:\ projects \ opencv-python \ opencv \ modules \ imgproc \ src \ hough.cpp:1728:错误:(-215:断言失败)!_image.empty()&&函数'cv :: HoughCircles'中的_image.type()== CV_8UC1 &&(_image.isMat()|| _image.isUMat())
答案 0 :(得分:0)
您可以尝试使用opencv而不是pil读取图像。
它看起来像这样:
import cv2
import numpy as np
gray = cv2.imread('coin.png', 0) # The zero reads the image in gray scale
gray = cv2.resize(gray,None,fx=0.25, fy=0.25, interpolation = cv2.INTER_CUBIC)
img = cv2.medianBlur(gray,1)
img = cv2.medianBlur(gray,1)
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20,
param1=30,
param2=15,
minRadius=0,
maxRadius=0)
print (circles)
我不确定您要在if语句中做什么。但是我认为您也应该更改此设置,因为未定义center_x和center_y。
HoughCircles还将返回一个Numpy数组,因此您不能使用!= None
,我认为这会更好。
center_x, center_y = [], []
if (len(circles) > 0):
i = np.uint16(np.around(circles))
cv2.circle(gray,(i[0,0,0],i[0,0,1]),i[0,0,2],(255,255,255),1)
cv2.circle(gray,(i[0,0,0],i[0,0,1]),1,(255,255,255),1)
center_x.append(i[0,0,0])
center_y.append(i[0,0,1])