Python---image read and write operations (scipy)

Here are just the operations commonly used in deep learning:

#read and save images operations
import them
import glob
import random
from scipy import misc
import numpy as np
import time
image_dir = r"C:\Users\Administrator\Desktop";
file_glob = os.path.join(image_dir,"images","training","*.jpg")
file_list = []
#Read the path of the qualified jpg file into file_list
file_list.extend(glob.glob(file_glob))
print(file_list[::])
print("-----------------------------------------------------------")
#Shuffle the file paths in the file_list and shuffle the order
random.shuffle(file_list)
print(file_list[::])

def read_andtransform(filename):
    image = misc.imread(filename)
    #Correct the image size to [100,100] size
    resize_image = misc.imresize(image,[220,220],interp = "nearest", mode = "RGB")
    #Save image operation 1
    #Use imsave to save the image object directly
    #path = "C:\\Users\\Administrator\\Desktop\\images\\res\\"+str(int(time.time())) + ".jpg"
    #misc.imsave(path, resize_image)

    # Convert the resize_image object to an array and return it
    return np.array(resize_image)

#Read all image files in file_list into the array images
images = np.array([read_andtransform(filename) for filename in file_list])
#Save all images in images
for i in range(len(images)):
    print(images[i].shape)
    #The method of saving the array as an image object:
    #Use the misc.toimage method to convert the array to an image object
    img = misc.toimage(images[i])
    #Use imsave to save the image object
    misc.imsave("C:\\Users\\Administrator\\Desktop\\images\\res\\"+str((time.time())) + ".jpg",img)
If Pillow is used, a simple image read and write operation is as follows:

import numpy as np
import them
from PIL import Image

#Use the open method to open the image
img = Image.open("C:\\Users\\Administrator\\Desktop\\images\\test.jpg")
# Simple operation on the image
#Define image pixel inversion effect function
def reverse(x):
    return 255 - x
#Use the eval method to invert the image
img1 = Image.eval(img,reverse)
#Use save to save
img1.save("C:\\Users\\Administrator\\Desktop\\images\\res.jpg")


#Get [x,y] position pixel rgb
x=10
y=10
rgb = img.getpixel((x,y))
#Assign the pixel at [x,y]
rgb_new = (100,200,255)
img.putpixel((x,y),rgb_new)
#Get rgb three-channel pixel array
channels = img.split()
r,g,b = channels
#Fusing the rgb three channels into a new image
img_new = Image.merge("RGB",(r,g,b))
The above is the method of using Scipy and PILLOW library for simple image manipulation. For more detailed introduction, please refer to the official documentation.



Guess you like

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