vanetoj
vanetoj

Reputation: 99

How to save a long list of images to a specific directory?

How do I save images to a specific directory? It's about 30,000 images that are split in subfolders. I read them with glob and cv2, added them to a list, then turned them into a NumPy array. Now I'm applying blur and need to add them to a specific directory. All I see is the PIL save example for a single image and it's not working for the list that I have. Any ideas? I converted them to NumPy arrays with this line of code: images = np.asarray(cv_img).

import numpy as np
import cv2

def motion_blur(image, degree=21, angle=11):
    image = np.array(image)

    # This generates a matrix of motion blur kernels at any angle. 
    # The greater the degree, the higher the blur.
    M = cv2.getRotationMatrix2D((degree / 2, degree / 2), angle, 1)
    motion_blur_kernel = np.diag(np.ones(degree))
    motion_blur_kernel = cv2.warpAffine(motion_blur_kernel, M, (degree, degree))

    motion_blur_kernel = motion_blur_kernel / degree
    blurred = cv2.filter2D(image, -1, motion_blur_kernel)

    # convert to uint8
    cv2.normalize(blurred, blurred, 0, 255, cv2.NORM_MINMAX)
    blurred = np.array(blurred, dtype=np.uint8)
    return blurred

img_ = motion_blur(images)

Upvotes: 0

Views: 2013

Answers (1)

Sameer Pusegaonkar
Sameer Pusegaonkar

Reputation: 143

Since you've saved the desired output in a numpy array, you can use the imwrite() method.

For multiple images.

import os
import cv2

count=0
DIR="C:\\Name_of_Folder\\"

for i in os.listdir(DIR):
    image=cv2.imread(os.path.join(DIR, i))
    blurred_image = motion_blur(image)
    cv2.imwrite('/path/to/destination/image'+str(count)+'.png',blurred_image) 
    count+=1

Upvotes: 1

Related Questions