gpt4 book ai didi

python - 用Canny在倾斜图像中寻找边缘

转载 作者:行者123 更新时间:2023-12-02 16:46:38 25 4
gpt4 key购买 nike

我试图在一系列图像中找到倾斜 Angular ,这些图像看起来像下面创建的示例数据。应该有一个肉眼可见的清晰边缘。但是到目前为止,我一直在努力提取边缘。 Canny是在此处找到边缘的正确方法还是在找到边缘的更好方法?

import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage.filters import gaussian_filter

# create data
xvals = np.arange(0,2000)
yvals = 10000 * np.exp((xvals - 1600)/200) + 100
yvals[1600:] = 100
blurred = gaussian_filter(yvals, sigma=20)

# create image
img = np.tile(blurred,(2000,1))
img = np.swapaxes(img,0,1)

# rotate image
rows,cols = img.shape
M = cv.getRotationMatrix2D((cols/2,rows/2),3.7,1)
img = cv.warpAffine(img,M,(cols,rows))

# convert to uint8 for Canny
img_8 = cv.convertScaleAbs(img,alpha=(255.0/65535.0))
fig,ax = plt.subplots(3)
ax[0].plot(xvals,blurred)
ax[1].imshow(img)

# find edge
ax[2].imshow(cv.Canny(img_8, 20, 100, apertureSize=5))

sample image for edge detection

最佳答案

您可以通过将图像转换为二进制(cv2.threshold(cv2.THRESH_BINARY))然后搜索轮廓来找到 Angular 。

enter image description here

找到轮廓(线)时,可以在轮廓cv2.fitLine()上拟合一条线,并获得该线的两个点。我的数学不是很好,但是我认为在线性方程中公式变为f(x) = k*x + n,您可以从这两个点(k)中获得k = (y2-y1)/(x2-x1),最后从 Angular phi = arctan(k)中获得。 (如果我错了,请更正)

您还可以使用旋转的边界矩形cv2.minAreaRect()-已经返回了矩形的 Angular (rect = cv2.minAreaRect()-> rect[2])。希望能帮助到你。干杯!

这是示例代码:

import cv2
import numpy as np
import math

img = cv2.imread('angle.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, threshold = cv2.threshold(gray,170,255,cv2.THRESH_BINARY)
im, contours, hierarchy = cv2.findContours(threshold,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
for c in contours:
area = cv2.contourArea(c)
perimeter = cv2.arcLength(c, False)
if area < 10001 and 100 < perimeter < 1000:
# first approach - fitting line and calculate with y=kx+n --> angle=tan^(-1)k
rows,cols = img.shape[:2]
[vx,vy,x,y] = cv2.fitLine(c, cv2.DIST_L2,0,0.01,0.01)
lefty = int((-x*vy/vx) + y)
righty = int(((cols-x)*vy/vx)+y)
cv2.line(img,(cols-1,righty),(0,lefty),(0,255,0),2)
(x1, y1) = (cols-1, righty)
(x2, y2) = (0, lefty)
k = (y2-y1)/(x2-x1)
angle = math.atan(k)*180/math.pi
print(angle)
#second approch - cv2.minAreaRect --> returns center (x,y), (width, height), angle of rotation )
rect = cv2.minAreaRect(c)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img,[box],0,(0,0,255),2)
print(rect[2])

cv2.imshow('img2', img)

原始图片:

enter image description here

输出:

enter image description here

-3.8493663478518627

-3.7022125720977783

关于python - 用Canny在倾斜图像中寻找边缘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51169162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com