试图找到发票/收据扫描图像的旋转角度,然后将其旋转到正确位置

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

Hi Iam trying to find the angle by which the scanned receipt or invoices are aligned and then getting it to the correct position....enter image description here图片说明:I want to find the angle of these two king of non line images angle of rotation please help

enter code here

import cv2`enter code here`
import numpy as np
import glob

def detect_angle(image):
    mask = np.zeros(image.shape, dtype=np.uint8)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (3,3), 0)
    adaptive = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,15,4)

    cnts = cv2.findContours(adaptive, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if len(cnts) == 2 else cnts[1]

    for c in cnts:
        area = cv2.contourArea(c)
        if area < 45000 and area > 20:
            cv2.drawContours(mask, [c], -1, (255,255,255), -1)

    mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
    h, w = mask.shape

    # Horizontal
    if w > h:
        left = mask[0:h, 0:0+w//2]
        right = mask[0:h, w//2:]
        left_pixels = cv2.countNonZero(left)
        right_pixels = cv2.countNonZero(right)
        return 0 if left_pixels >= right_pixels else 180
    # Vertical
    else:
        top = mask[0:h//2, 0:w]
        bottom = mask[h//2:, 0:w]
        top_pixels = cv2.countNonZero(top)
        bottom_pixels = cv2.countNonZero(bottom)
        return 90 if bottom_pixels >= top_pixels else 270

if __name__ == '__main__':
    filenames = [img for img in glob.glob(r"C:\Users\lenovo\Desktop\samples\images for oPEN CV/*.png")]

    filenames.sort() # ADD THIS LINE

    images = []
    for img in filenames:
        n= cv2.imread(img)
        images.append(n)
        print (img)
        image = cv2.imread(img)
        angle = detect_angle(image)
        print(angle)

python opencv
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.