pythonproject/create_iamge_border.py

69 lines
2.2 KiB
Python
Raw Normal View History

2024-06-25 14:15:07 +08:00
from PIL import Image, ImageOps
import cv2
import numpy as np
def add_yellow_border(image_path, output_path, border_size=2):
"""
给指定的图像添加黄色外边框并保存
参数:
image_path (str): 原始图像的路径
output_path (str): 带边框的图像保存路径
border_size (int): 边框的像素宽度默认为2
"""
# 打开图像
img = Image.open(image_path)
# 计算边框颜色和大小
# 灰色
# border_color = (192, 192, 192)
border_color = (255, 255, 0)
border = (border_size, border_size, border_size, border_size) # (左, 上, 右, 下)
# 添加边框
img_with_border = ImageOps.expand(img, border=border, fill=border_color)
# 保存新图像
img_with_border.save(output_path)
print(f"Image saved with a yellow border to {output_path}")
def find_qr_code_border_and_save(image_path):
# 读取图像
img = cv2.imread(image_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 边缘检测
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
# 霍夫变换检测直线
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, threshold=100, minLineLength=100, maxLineGap=10)
print(lines)
# 初始化最小和最大的x和y值
min_x, max_x = img.shape[1], 0
min_y, max_y = img.shape[0], 0
if lines is not None:
# 更新x和y的最小和最大值来找到边界框
for line in lines:
x1, y1, x2, y2 = line[0]
min_x = min(min_x, x1, x2)
max_x = max(max_x, x1, x2)
min_y = min(min_y, y1, y2)
max_y = max(max_y, y1, y2)
# 截取二维码区域
qr_code_region = img[min_y:max_y, min_x:max_x]
# 保存截取的图片
cv2.imwrite('qr_code_detected.png', qr_code_region)
print("二维码区域已保存为 'qr_code_detected.png'")
else:
print("未检测到任何直线")
# 示例用法
# image_path = '20240506202950.png' # 替换为你的图像路径 jkkkkkkkkkk
# output_path = '20240506202950_border.png' # 替换为保存新图像的路径
# add_yellow_border(image_path, output_path,5)
find_qr_code_border_and_save('IMG_3565.png')