简体   繁体   中英

Take images from a directory, crop and save all images in the directory

I am trying to crop high-resolution images to something more manageable. I am trying to read in a directory rather than individual images and save the new cropped images in another directory. I would like to make all the output images as.png as I have in my code.

import cv2

path = './imgs2/P5.png'
img= cv2.imread (path)
imgcropped = img [1:400, 1:400]
cv2.imwrite ('./imgs/P5-cropped', imgcropped)

Any help with this problem is appreciated.

Here's what I use in this case:

import os
import cv2

path = 'path/to/image/dir/'
dest_path = 'path/to/destination/'

for f in os.listdir(path):
    image = cv2.imread(os.path.join(path, f))
    imgcropped = image[1:400, 1:400]
    cv2.imwrite(os.path.join(dest_path, f), imgcropped)

Assuming that:

  • the images in path are already.png
  • path contains only the images you want to convert

os.listdir will give you the names of the files inside your origin dir (including extension), which you can use in imwrite to save the image in your destination dir with the same filename.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM