数字图像预处理代码梳理

二值化:

imgcut = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thrpic = 255 - cv2.adaptiveThreshold(imgcut, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                         cv2.THRESH_BINARY, 31, 11)

*边缘检测 *

#输入是二值化后的图片
 thrpic = cv2.Canny(thrpic, 20, 250)

直线检测

def drawlines(img, name):
    edges = cv2.Canny(img, 50, 200)
    minLINELENGTH = 20
    #lines = cv2.HoughLinesP(edges, 1, np.pi / 180, minLINELENGTH, 0)
    lines = cv2.HoughLines(edges, 1, np.pi / 180, 80)
    if lines is not None:
        print(name, "'s line:", len(lines))
        for line in lines:
            rho, theta = line[0]
            a = np.cos(theta)
            b = np.sin(theta)
            x0 = a * rho
            y0 = b * rho
            x1 = int(x0 + 1000 * (-b))
            y1 = int(y0 + 1000 * (a))
            x2 = int(x0 - 1000 * (-b))
            y2 = int(y0 - 1000 * (a))
            # 绘制直线
            cv2.line(img, (x1, y1), (x2, y2), (255, 255, 255), 2)
            #将直线改为与背景色一直
    return img
           #摆正图像, 倾斜旋转
           if x1 == x2 or y1 == y2:
                break
            t = float(y2 - y1) / (x2 - x1)
            rotate_angle = math.degrees(math.atan(t))
            print("angel:", rotate_angle)
            if rotate_angle > 0.5 or rotate_angle < -0.5:
                img = ndimage.rotate(img, rotate_angle)

你可能感兴趣的:(数字图像处理)