用Canny在倾斜图像中找到边缘

问题描述 投票:0回答:4

我试图在一系列图像中找到倾斜角度,这些图像看起来像下面创建的示例数据。眼睛应该有清晰的边缘。然而,到目前为止,我正在努力提取边缘。 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

python opencv edge-detection canny-operator
4个回答
3
投票

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

enter image description here

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

您还可以使用旋转的边界矩形 - cv2.minAreaRect() - 它已经返回矩形的角度(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


2
投票

TRIBOL,

看起来你可以拍摄渐变图像G = | Gx | + | Gy | (将其标准化为某个已知范围),计算其直方图并取出它的顶部区域。它会给你近线的面具。然后你可以做线条拟合。它会给你一个很好的初步猜测。


0
投票

一个非常简单的方法如下...调整我的数字以适应您对数据的了解。

将图像标准化为0-255的标度。

选择两个点A和B,其中A是左侧图像宽度的10%,B是右侧10%。距离AB现在是0.8 x 2000,或1600 px。

从A点向北移动您的图像采样,直到您超过某个合理的阈值,这意味着您已经遇到了倾斜线。注意此时的Y值,如YA。

做同样的事情,从B点向北走,直到遇到倾斜线。注意此时的Y值,为YB。

你寻求的角度是:

tan-1((YB-YA)/1600) 

enter image description here


0
投票

由kavko建议的阈值效果不好,因为图像之间的强度不同(我当然可以考虑每个图像的直方图来改进这种方法)。我最终采用了y方向上的最大梯度:

def rotate_image(image):
    blur = ndimage.gaussian_filter(image, sigma=10)    # blur image first
    grad = np.gradient(blur, axis= 0)    # take gradient along y-axis
    grad[grad>10000]=0    # filter unreasonable high values
    idx_maxline = np.argmax(grad, axis=0)    # get y-indices of max slope = indices of edge

    mean = np.mean(idx_maxline)
    std = np.std(idx_maxline)
    idx = np.arange(idx_maxline.shape[0])
    idx_filtered = idx[(idx_maxline < mean+std) & (idx_maxline > mean - std)]    # filter positions where highest slope is at different position(blobs)
    slope, intercept, r_value, p_value, std_err = stats.linregress(idx_filtered, idx_maxline[idx_filtered])
    out = ndimage.rotate(image,slope*180/np.pi, reshape = False)
    return out
out = rotate_image(img)
plt.imshow(out)

final rotated image

© www.soinside.com 2019 - 2024. All rights reserved.