Hongmu Notes
Home Language Notes Python batch cuts the left and right sides of pictures
Language Notes Summary of pitfalls python

Python batch cuts the left and right sides of pictures

Python batch cuts the left and right sides of pictures

Python automatically detects the distance between two sides of a picture:

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 cuts the left and right code in batches:

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

 

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

Import " requests" could not be resolved from source

Import " requests" could not be resolved from source Language Notes python

This error occurred when using Pylance, a Python language server. Among them, " Import " requests" could not be resolved from source" This error message indicates that the requests module is referenced in your code, but Pylance cannot find the location of the module from the source. The possible reason is that you don't have an …
👁 1771
Reinstall Python and requests libraries

Reinstall Python and requests libraries Language Notes python

If you meet " Import " requests" could not be resolved from source" You can try reinstalling Python and requests libraries. First, you need to uninstall the current Python and requests libraries. On Windows systems, you can use the command prompt …
👁 439
WARNING: Skipping requests as it is not installed.

WARNING: Skipping requests as it is not installed. Language Notes python

This error message indicates that your Python environment lacks the requests library, and this library is called in your code, so Python cannot execute your code normally. The solution to this problem is to install the requests library. You can use the pip command on the command line to install: pip install requests If you are using Python3, you can use the pip3 command …
👁 2100
Python reported an error. What is the reason? AttributeError: partially initialized module ' openai'  has no attribute ' Completion' (most likely due to a circular import)

Python reported an error. What is the reason? AttributeError: partially initialized module ' openai' has no attribute ' Completion' (most likely due to a circular import) Language Notes python

This error prompt indicates that there is a problem when importing the openai module and the specific Completion attribute, which is probably caused by circular import. The reason for this error may be that two or more modules in your code are imported from each other, forming a circular dependency. For example, module A imports module B, and module B imports module A.. Cyclic import will cause the module not to initialize correctly when loading, thus …
👁 656
How does python package and run on Windows?

How does python package and run on Windows? Language Notes python

The most common way to package and run Python programs on Windows is to use PyInstaller. PyInstaller is a free and cross-platform Python application packaging tool, which can package Python code and its dependent libraries into an independent executable file, making it possible to run Python programs on systems without Python interpreters installed. The following is to make …
👁 300
What programming software is good for python development?

What programming software is good for python development? Language Notes python

There are many programming softwares developed by Python. The following are some commonly used Python integrated development environments (IDE) and editors: PyCharmPyCharm is an integrated development environment developed by JetBrains, which is specially designed for Python developers. PyCharm is powerful and provides a series of advanced functions such as code completion, debugging, version control, code refactoring, etc., which can help developers improve their work …
👁 175

Recommended reading

Responsive playground children's toy website template 0963

Responsive playground children's toy website template 0963 Practical Collection Yiyou template

This set of eyoucms responsive templates is suitable for amusement parks and children's toy industries. The design style is lively and childlike, and it can display amusement facilities, toy products, brand stories and safety standards. It is helpful for children's entertainment brands to attract home consumers online. Template Display Installation Instructions Website Background: /login.php Account: admin Password: admin Related Articles Easy CMS Installation FAQ Summary Easy CMS(Ey…
👁 58
(Self-adaptive mobile phone terminal) logistics, transportation, express delivery and warehousing website template-with three-level column 0980

(Self-adaptive mobile phone terminal) logistics, transportation, express delivery and warehousing website template-with three-level column 0980 Practical Collection pbootcms Template

A logistics transportation express warehouse PbootCMS website template, supporting PC and WAP, with three columns. The design style is efficient and modern, which is suitable for express delivery and warehousing companies to show their service network and distribution strength. It is helpful for logistics enterprises to display their brands online and attract e-commerce and corporate customers. Template display installation instructions website background: /admin.php account number: admin password: admin decompression password: www.4s5…
👁 74
Logo image management of Imperial cms website is convenient for subsequent uploading and replacement (use of image information management and PHP call).

Logo image management of Imperial cms website is convenient for subsequent uploading and replacement (use of image information management and PHP call). Program Notes Empire cms

It is inconvenient to use extended variables to manage imperial pictures. Therefore, you can use the empire's own plug-in: picture information management. Usage, as shown above, but more introduction! Here is the calling method! & lt; div class=" logo fl w_img" & gt; & lt; ? php $img=$empire-& gt; fetch1(" SELECT * FROM…
👁 388
Website template of children's education and training institutions 0375

Website template of children's education and training institutions 0375 Practical Collection Yiyou template

This set of eyoucms template is suitable for children's education and training institutions, with a lively design style, which can show children's training courses, teaching environment, teachers and students' achievements. It is helpful for children's educational institutions to attract parents online and enhance their brand image. Template Display Installation Instructions Website Background: /login.php Account: admin Password: admin Related Articles Easy CMS Installation FAQ Summary Easy CMS(E…
👁 54
(Adaptive Mobile) Hardware Machinery Website pbootcms Template Blue Marketing Hardware Accessories Website Source Download 0427

(Adaptive Mobile) Hardware Machinery Website pbootcms Template Blue Marketing Hardware Accessories Website Source Download 0427 Practical Collection pbootcms Template

This set of self-adaptive mobile hardware machinery and blue marketing hardware accessories PbootCMS website template. Professional marketing design style, suitable for hardware accessories enterprises to display products, technical parameters and brands. It is helpful for hardware manufacturing enterprises to show their strength online and attract industrial customers. Template display installation instructions website background: /admin.php account number: admin password: admin decompression password: www.4s5.cn Xiang …
👁 43
Responsive leather custom handbags and purses website template 0964

Responsive leather custom handbags and purses website template 0964 Practical Collection Yiyou template

An eyoucms responsive website template for leather customization, handbags and purses industries. The design style is high-end and fashionable, and it can display leather products, customized services, brand stories and design concepts. It is helpful for leather goods brands to attract quality life consumers online. Template display installation instructions website background: /login.php account number: admin password: admin related articles Yiyou CMS installation FAQ summary Yiyou CM…
👁 39