0

I would like to add noise to every image inside a folder and save them to a new directory afterwards, I have a function that i found in another question that adds the exact noise that i need, however i need to load and save the images with noise added to them, in different directories:

AttributeError: 'list' object has no attribute 'shape'

The function actually uses arrays, and i am using PIL to load images, how can i get around this issue?

def sp_noise(image,prob):
    output = np.zeros(image.shape,np.uint8)
    thres = 1 - prob 
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            rdn = random.random()
            if rdn < prob:
                output[i][j] = 0
            elif rdn > thres:
                output[i][j] = 255
            else:
                output[i][j] = image[i][j]
    return output

    def loadimage(folder):
        images = []
        for filename in os.listdir(folder):
            img = cv2.imread(os.path.join(folder,filename))
            if img is not None:
                img = cv2.resize(img,(81,151))
                images.append(img)
                img = sp_noise(img, 0.10)
                cv2.imwrite(filepath, img)
                img.save('C:/Users/Images/Image-set1/'+filepath, 'JPEG')
        return images

loadimage = 'root folder from the images to be loaded and added noise to'

I tried using PIL but PIL deals with the image as an object, whereas this function is trying to deal with the images by treating them as arrays.

John Jones
  • 60
  • 3
  • 16
  • 1
    you can convert pil images to arrays with `np.array(pil_image)` and after adding the noise, you can convert back to pil again with `Image.fromarray(your_array)`. I recommend you to usee opencv because opencv deals with images as arrays, it can remove the overhead for you (if you don't have a specific reason to use pil). Also see this post, https://stackoverflow.com/questions/10965417/how-to-convert-a-numpy-array-to-pil-image-applying-matplotlib-colormap – Hasan Salim Kanmaz Aug 22 '20 at 18:40
  • No, not really, i dont have any specific reason to use PIL, the problem with openCV, is that i would need to save images one by one, i have no idea how to do it for every image from a folder – John Jones Aug 22 '20 at 18:58
  • 1
    btw i followed what you said, works like a charm thank you very much. – John Jones Aug 22 '20 at 19:09
  • The functions are properly working, make sure the folder contains only images. – Ahx Aug 22 '20 at 19:18

0 Answers0