Conversion between PIL.Image and numpy.array of image processing

After using PIL.Image.open() to open the image, if you want to use the img.shape function, you need to convert the image form into an array first

img = numpy.array(im)
For example, to add salt and pepper noise

    for k in range(n):
        i = int(numpy.random.random() * img.shape[1]);
        j = int(numpy.random.random() * img.shape[0]);
        if img.ndim == 2:
            img[j,i] = 255
        elif img.ndim == 3:
            img[j,i,0]= 255
            img[j,i,1]= 255
            img[j,i,2]= 255

Finally convert the array to inage form

img = Image.fromarray(img.astype('uint8')).convert('RGB')


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324795572&siteId=291194637