Home > other >  Loading images from a directory and applying translation to grey scale images
Loading images from a directory and applying translation to grey scale images

Time:12-05

I have a folder with a set of images and I would like to load all images and convert them to grey scale and apply shifting to my images and save them to a new directory.

What I have tried was using glob glob to load the images but I don't know how to apply affine transformation to my images:

import glob
import os
cv_img = []
for img in glob.glob("path/*.tiff"):
    cv_img.append(img)
    print(cv_img.shape)
    for i in rangef(0.70, 1.50, 0.0025): 
        img = clipped_zoom(cv_img, i)
        new_im = Image.fromarray(img)
        new_im.save('path/imagezoom%s.tif'%(j,))

How can i do the same but for image image shifting and grey scale conversion?

CodePudding user response:

firstly you can use os.walk. It will search folders and subfolders in a directory and then you can append the images as an array to a list. However, you can also use PIL to open your image and convert them to 'L', it will give you a grey scale image. You can also use cv2 to perform the shifting image.

directory = 'your path'
for root, dirs, files in os.walk(directory):
    for filename in files:
        path = os.path.join(root, filename)
        img = Image.open(path).convert('L') 
 // convert image to grey scale
        img_array = np.copy(np.asarray(img))
        for i in range(1): 
            try:
                for j in rangef(1, 120, 1):
                    num_rows, num_cols = np.copy(img_array.shape[:2])
                    translation_matrix = np.float32([ [1,0, j], [0,1,0] ])
                    img_t = cv2.warpAffine(img_array, translation_matrix, (num_cols, num_rows))
                    img = Image.fromarray(img_t)
                    img.save('yourpath.../image_shift_%s.tif'%(j,))  
            except EOFError:
                break
  • Related