python自动检测图片两侧距离的代码:
import cv2
import numpy as np
image_path = r"C:\Users\18102\Downloads\ok\0001.png" # 请改为实际的一张截图路径
img = cv2.imread(image_path)
if img is None:
print("无法读取图片,请检查路径")
exit()
clone = img.copy()
points = [] # 存储两个点击点
def click_event(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
points.append((x, y))
cv2.circle(clone, (x, y), 5, (0, 0, 255), -1)
cv2.putText(clone, f"({x},{y})", (x+10, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,0,255), 2)
cv2.imshow("Image", clone)
print(f"已记录点: ({x}, {y})")
if len(points) == 2:
# 计算左右裁剪量
x1, y1 = points[0]
x2, y2 = points[1]
left_crop = min(x1, x2) # 左边裁剪宽度
right_crop = img.shape[1] - max(x1, x2) # 右边裁剪宽度
print("\n========== 裁剪参数 ==========")
print(f"左侧应裁剪宽度: {left_crop}px")
print(f"右侧应裁剪宽度: {right_crop}px")
print("================================")
cv2.destroyAllWindows()
cv2.namedWindow("Image", cv2.WINDOW_NORMAL)
cv2.imshow("Image", clone)
cv2.setMouseCallback("Image", click_event)
print("请依次点击:\n1. 左侧可见内容的左边缘(要保留的起始点)\n2. 右侧滚动条内侧边缘(要保留的结束点)")
cv2.waitKey(0)
cv2.destroyAllWindows()
python批量剪切左右两侧的代码:
import os
import cv2
# ---------- 配置 ----------
input_dir = r"C:\Users\18102\Downloads\ok"
output_dir = r"C:\Users\18102\Downloads\ok_cropped"
LEFT_CROP = 159
RIGHT_CROP = 140
# ---------- 创建输出目录 ----------
os.makedirs(output_dir, exist_ok=True)
# 获取所有 PNG 文件列表
png_files = [f for f in os.listdir(input_dir) if f.lower().endswith('.png')]
total = len(png_files)
if total == 0:
print("❌ 没有找到任何 PNG 图片,请检查目录。")
exit()
print(f"📁 找到 {total} 张 PNG 图片。")
# ---------- 先处理前 3 张 ----------
sample_count = min(3, total)
print(f"\n🔄 正在处理前 {sample_count} 张作为预览...")
for i in range(sample_count):
filename = png_files[i]
src_path = os.path.join(input_dir, filename)
img = cv2.imread(src_path, cv2.IMREAD_UNCHANGED)
if img is None:
print(f"⚠️ 跳过无法读取的文件: {filename}")
continue
h, w = img.shape[:2]
left = LEFT_CROP
right = w - RIGHT_CROP
if left >= right:
print(f"⚠️ 警告:{filename} 裁剪后宽度为0,跳过")
continue
cropped = img[:, left:right]
dst_path = os.path.join(output_dir, filename)
cv2.imwrite(dst_path, cropped)
print(f"✅ 已处理: {filename} -> 新尺寸 ({cropped.shape[1]}, {cropped.shape[0]})")
print(f"\n📂 预览图片已保存到: {output_dir}")
print("请打开该目录查看前 3 张图片的裁剪效果。")
# ---------- 询问是否继续 ----------
while True:
choice = input("\n是否继续处理剩余图片?(y/n,默认 y): ").strip().lower()
if choice in ('y', 'yes', ''):
break
elif choice in ('n', 'no'):
print("已取消,退出脚本。")
exit()
else:
print("请输入 y 或 n。")
# ---------- 处理剩余图片 ----------
print(f"\n🔄 正在处理剩余 {total - sample_count} 张图片...")
for i in range(sample_count, total):
filename = png_files[i]
src_path = os.path.join(input_dir, filename)
img = cv2.imread(src_path, cv2.IMREAD_UNCHANGED)
if img is None:
print(f"⚠️ 跳过无法读取的文件: {filename}")
continue
h, w = img.shape[:2]
left = LEFT_CROP
right = w - RIGHT_CROP
if left >= right:
print(f"⚠️ 警告:{filename} 裁剪后宽度为0,跳过")
continue
cropped = img[:, left:right]
dst_path = os.path.join(output_dir, filename)
cv2.imwrite(dst_path, cropped)
print(f"✅ 已处理: {filename} -> 新尺寸 ({cropped.shape[1]}, {cropped.shape[0]})")
print(f"\n🎉 全部处理完成!共处理 {total} 张图片。")
print(f"📁 输出目录: {output_dir}")
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END








![表情[aoman]-红穆笔记](https://www.4s5.cn/wp-content/themes/zibll/img/smilies/aoman.gif)



暂无评论内容