opencv batch modify image resolution

How to modify image resolution in batches using Python's OpenCV

In image processing and computer vision, it is often necessary to process a large amount of image data, and one of the common needs is to modify the resolution of the image. Python's OpenCV library provides some convenient functions that can help us modify the resolution of images in batches. This article will show how to use Python's OpenCV library to achieve this function.

1. Install the OpenCV library

First, make sure you have installed Python and the OpenCV library. If you have not installed the OpenCV library, you can install it with the following command:

pip install opencv-python

2. Import the OpenCV library and other necessary libraries

Next, at the beginning of the code, we need to import the OpenCV library and other necessary libraries:

import cv2
import os

3. Set the input and output directories

Before starting to batch modify image resolutions, we need to set the input and output directories. The input directory is the path to the folder containing the images to be processed, and the output directory is the path to the folder where the processed images are saved. We can use osthe library to create a directory:

input_folder = 'input/'
output_folder = 'output/'

os.makedirs(output_folder, exist_ok=True)

4. Modify image resolution in batches

Now, we can modify the image resolution in batches. We can use cv2.resize()the method to modify the resolution of the image. This method takes in an image, a target width, and a target height. Here is a sample code:

for filename in os.listdir(input_folder):
    if filename.endswith('.jpg') or filename.endswith('.png'):
        image = cv2.imread(os.path.join(input_folder, filename))
        resized_image = cv2.resize(image, (640, 480))
        cv2.imwrite(os.path.join(output_folder, filename), resized_image)

The above code traverses all image files in the input directory to determine whether they end with '.jpg' or '.png', and then use the cv2.resize()method to modify the resolution of the image and save it to the output directory.

5. Conclusion

By using Python's OpenCV library, we can easily implement the function of modifying image resolution in batches. Only need to set the input and output directory, and call the corresponding function, you can quickly process image data in batches. Hope this article can help you better understand and use Python's OpenCV library.

以下是一个小示例

import cv2
import os

path = r"C:\Users\lenovo\Desktop\gg"  # 存放原图片的文件夹路径
list = os.listdir(path)
for index, i in enumerate(list):
    path = r"C:\Users\lenovo\Desktop\gg\{}".format(i)
    img = cv2.imread(path)
    img = cv2.resize(img, (480, 640))  # 修改为480*640
    path = r"C:\Users\lenovo\Desktop\kk\{}.jpg".format(index) # 处理后的图片文件夹路径
    cv2.imwrite(path, img)

To understand some simple operations of os, you can refer to this post

Guess you like

Origin blog.csdn.net/m0_46114594/article/details/116310027