How to write and transform image files from one directory to another directory using open cv?

Viewed 114

I am attempting to copy and apply a horizontal transformation to all images from one of my directories (directory_a), and then write them to another (directory_b) using cv2. All images are in png format. This is my first time using open cv/cv2.

When I use the code I currently have (see below), the transformation is applied but the images are saved to the same directory. Does anyone know how to properly do this?

from glob import glob
import cv2

#Flip Image horizontally and add Image to directory_b Folder

directory_a = '/content/drive/MyDrive/no_copies2/train/directory_a_images'
directory_b = '/content/drive/MyDrive/no_copies2/train/directory_b_images'

input_files = glob(os.path.join(directory_a, "*.png"))

for file in input_files:
    img = cv2.imread(file)
    horizontal_img = cv2.flip(img, 1)   
    cv2.imwrite(os.path.join(directory_b, file + '_flip_v' + '.png'), horizontal_img)
2 Answers

file variable is holding the path to the whole path, try:

cv2.imwrite(os.path.join(directory_b, os.path.basename(file).split(".")[0] + '_flip_v' + '.png'),
            horizontal_img)

It might have to do with Google Colab. Make sure you have all directories created before running the code. I previously tried doing something similar and not setting up the directories properly in the drive came with some issues.

Related