本帖最后由 ljkund 于 2023-11-17 11:07 编辑
我是一个小白,使用chatgpt+星火大模型+人工修改拼出来的代码,功能是选择一个文件夹,自动识别文件夹内所有图片是否包含二维码(白色的二维码识别不了),识别后自动裁剪掉其他部分,保存到目录下output文件夹。
兰州云:https://wwjf.lanzoul.com/ignGZ1f1a11a
123云盘:https://www.123pan.com/s/75pfjv-VAffv.html
因为最近要收集大量的二维码和处理,所以开发了这个,打包exe之后多了很多运行库,有能力的可以优化一下体积,理论上可以给白色的二维码进行反色之后再裁剪是没问题的,但我遇到了很多报错就没做了,抱歉,代码如下:
[Python] 纯文本查看 复制代码 import cv2
import numpy as np
import os
import uuid
from tkinter import filedialog
from tkinter import Tk
def crop_qr_code(image_path, output_dir):
# Load the image using OpenCV
image = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), -1)
# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Use OpenCV's method to find QR code aligners
detector = cv2.QRCodeDetector()
retval, points = detector.detect(gray)
if points is not None:
# Find the top-left and bottom-right points of the QR code
points = points[0]
top_left = np.min(points, axis=0)
bottom_right = np.max(points, axis=0)
# Crop the region containing the QR code
qr_code = image[int(top_left[1]):int(bottom_right[1]), int(top_left[0]):int(bottom_right[0])]
# Generate a random filename
source_filename = os.path.basename(image_path)
output_filebasename, _ = os.path.splitext(source_filename)
output_filename = output_filebasename + ".jpg"
output_path = os.path.join(output_dir, output_filename)
# Save the cropped image
cv2.imencode('.jpg', qr_code)[1].tofile(output_path)
print(f"QR code cropped and saved to {output_path}")
else:
print(f"No QR code detected in {image_path}.")
def crop_qr_codes_in_directory(input_dir, output_dir):
# Check if output directory exists, if not create it
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Process each file in the directory
for filename in os.listdir(input_dir):
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.tiff')):
image_path = os.path.join(input_dir, filename)
crop_qr_code(image_path, output_dir)
# Set your input directory and output directory here
root = Tk()
root.withdraw()
input_directory = filedialog.askdirectory()
output_directory = os.path.join(input_directory, 'output')
# Crop QR codes for all images in the input directory
crop_qr_codes_in_directory(input_directory, output_directory)
下面是针对白色二维码的代码,可以自动识别文件夹中所有没有二维码的图片(白色的)然后进行反色处理
[Python] 纯文本查看 复制代码 import os
import cv2
import numpy as np
import pyzbar.pyzbar as pyzbar
def is_qrcode(image):
# 对大图像进行缩放
height, width = image.shape[:2]
if height * width > 1000 * 1000: # 例如,对于超过 1000x1000 像素的图像
image = cv2.resize(image, (width // 2, height // 2))
# 可选的图像预处理
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, thresholded = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
decoded_objects = pyzbar.decode(thresholded)
return len(decoded_objects) > 0
def invert_colors(image):
return cv2.bitwise_not(image)
def process_images():
for file in os.listdir('.'):
if file.lower().endswith(('.jpg', '.jpeg', '.png')):
file_path = os.path.join('.', file)
file_path_encoded = file_path.encode('utf-8')
image = cv2.imdecode(np.fromfile(file_path_encoded, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
if image is not None and not is_qrcode(image):
inverted_image = invert_colors(image)
_, buf = cv2.imencode(os.path.splitext(file)[1], inverted_image)
buf.tofile(file)
if __name__ == '__main__':
process_images() |