当前位置:   article > 正文

Python OpenCV 批量裁剪图片某一指定区域并存储_python opencv crop

python opencv crop

在函数中修改起始点坐标start_x, start_y,以及裁剪区域长宽

import argparse
import os
import cv2


def crop_and_save_images(directory, outputdir):
    """
    Crop the same region from multiple images in the given directory and save the cropped images,
    overwriting the original images.

    Args:
    directory: Path to the directory containing the images.
    outputdir: Path to the directory containing the output images.
    """
    # Get a list of all image files in the directory
    image_files = [f for f in os.listdir(directory) if f.endswith('.jpg') or f.endswith('.png')]

    # Read the first image to determine the region to crop
    first_image_path = os.path.join(directory, image_files[0])
    first_image = cv2.imread(first_image_path)

    # Define the region of interest (ROI) to crop (example: top-left corner)
    roi = (450, 350, 500, 400)  # Format: (start_x, start_y, width, height)

    # Crop and save each image
    for image_file in image_files:
        image_path = os.path.join(directory, image_file)
        image = cv2.imread(image_path)
        print("processing " + image_path)

        # Crop the region of interest
        cropped_image = image[roi[1]:roi[1] + roi[3], roi[0]:roi[0] + roi[2]]

        # Overwrite the original image with the cropped region
        cv2.imwrite(os.path.join(outputdir,image_file), cropped_image)

def main():
    directory = "test"
    outputdir = "outputtest"
    crop_and_save_images(directory, outputdir)

if __name__ == "__main__":
    main()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/678663
推荐阅读
相关标签
  

闽ICP备14008679号