import cv2 as cv import os import cv2 # 这个是裁剪图片类 def crop_qrcode_images(input_path, output_path): # 遍历该目录下的所有图片文件 for filename in os.listdir(input_path): src = cv.imread(os.path.join(input_path, filename)) gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY) # 通过二值化得到二维码区域 _, thresh = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV + cv.THRESH_OTSU) # 查找轮廓并选出最大的轮廓 contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) max_contour = max(contours, key=cv.contourArea) # 找到包围最大轮廓的矩形并计算出其宽高比 x, y, w, h = cv.boundingRect(max_contour) aspect_ratio = w / h # 如果宽高比符合二维码标准,就将该矩形作为二维码区域进行裁剪 # if 0.9 <= aspect_ratio <= 1.1: dst = src[y:y + h, x:x + w] # print(max_contour) # 检查并创建目标文件夹 output_dir = os.path.join(input_path, "tugai") if not os.path.exists(output_dir): os.makedirs(output_dir) # 保存裁剪后的图像 output_filename = os.path.join(output_dir, filename) cv.imwrite(output_filename, dst) yield output_filename # 遍历输入路径下的所有图片(路径文件名不能有中文),并进行裁剪操作,输出至子文件夹"qrcode_cropped" input_path = r"C:/Users/ohnb/Desktop/tu" output_path = os.path.join(input_path, "tugai") try: for cropped_image_path in crop_qrcode_images(input_path, output_path): print("裁剪后的图像已保存至:", cropped_image_path) except: print("文件夹里存在中文图片或者文件夹里有子文件夹")
图片裁剪ocr
于 2023-07-26 09:54:02 首次发布