import cv2
import numpy as np
# read image as grayscale
img = cv2.imread('sunset.jpg')
hh, ww = img.shape[:2]
# shave off white region on right side
img = img[0:hh, 0:ww-2]
# convert to gray
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# median filter
median = cv2.medianBlur(gray, 3)
# do canny edge detection
canny = cv2.Canny(median, 100, 200)
# get canny points
# numpy points are (y,x)
points = np.argwhere(canny>0)
# get min enclosing circle
center, radius = cv2.minEnclosingCircle(points)
print('center:', center, 'radius:', radius)
# draw circle on copy of input
result = img.copy()
x = int(center[1])
y = int(center[0])
rad = int(radius)
cv2.circle(result, (x,y), rad, (255,255,255), 1)
# write results
cv2.imwrite("sunset_canny.jpg", canny)
cv2.imwrite("sunset_circle.jpg", result)
# show results
cv2.imshow("median", median)
cv2.imshow("canny", canny)
cv2.imshow("result", result)
cv2.waitKey(0)
import cv2
import numpy as np
# read image as grayscale
img = cv2.imread('sunset.jpg')
hh, ww = img.shape[:2]
# shave off white region on right side
img = img[0:hh, 0:ww-2]
# convert to gray
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# median filter
median = cv2.medianBlur(gray, 3)
# do canny edge detection
canny = cv2.Canny(median, 100, 250)
# transpose canny image to compensate for following numpy points as y,x
canny_t = cv2.transpose(canny)
# get canny points
# numpy points are (y,x)
points = np.argwhere(canny_t>0)
# fit ellipse and get ellipse center, minor and major diameters and angle in degree
ellipse = cv2.fitEllipse(points)
(x,y), (d1,d2), angle = ellipse
print('center: (', x,y, ')', 'diameters: (', d1, d2, ')')
# draw ellipse
result = img.copy()
cv2.ellipse(result, (int(x),int(y)), (int(d1/2),int(d2/2)), angle, 0, 360, (0,0,0), 1)
# draw circle on copy of input of radius = half average of diameters = (d1+d2)/4
rad = int((d1+d2)/4)
xc = int(x)
yc = int(y)
print('center: (', xc,yc, ')', 'radius:', rad)
cv2.circle(result, (xc,yc), rad, (0,255,0), 1)
# write results
cv2.imwrite("sunset_canny_ellipse.jpg", canny)
cv2.imwrite("sunset_ellipse_circle.jpg", result)
# show results
cv2.imshow("median", median)
cv2.imshow("canny", canny)
cv2.imshow("result", result)
cv2.waitKey(0)
下面是在Python/OpenCV中获得代表性圆的一种方法。它找到最小的封闭圆
输入:
精明的边缘:
结果圆:
备选方案
将椭圆拟合到Canny点,然后得到圆半径的两个椭圆半径的平均值。请注意,精明的论点中有一个细微的变化,即只得到日落的顶部
Canny边缘图像:
输入时绘制的椭圆和圆:
首先使用Canny edge。然后在边缘图像上尝试Hough圆或Hough椭圆。这些都是蛮力方法,所以速度很慢,但它们对非圆形或非椭圆形轮廓有抵抗力。您可以轻松过滤结果,使检测到的结果在最亮点附近有一个中心。此外,了解太阳的估计大小将有助于提高计算速度
您还可以研究使用
cv2.findContours
和cv2.approxPolyDP
从图像中提取连续轮廓。您可以通过周长和形状进行过滤,然后运行最小二乘拟合或Hough拟合编辑
在Canny边缘检测之前尝试强度过滤器可能是值得的。我怀疑它会大大清理边缘图像
相关问题 更多 >
编程相关推荐