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}")