简体   繁体   中英

How to sort the images using one of the average pixels in python PIL

I'm on the way to sorting several images according to their average pixel values using PIL. In the below code I choose to pick up the average red value as the prameter to sort the images. The images are all in 640 x 480 RBG format. I have 10 images (from GRK_image1 to GRK_image10), instead of typing the code below 10 times, is there any faster way to loop through all the 10 images in one step and get all the average red values for each image? I have been stuck here for many days. Thank you!

from PIL import Image
import glob

# 1. Get the first picture, open it

first_image=Image.open('GRK_imge1.png')

all_pixels = []
for x in range(640):
  for y in range(480):
    R, G, B = convert_first_image.getpixel((x,y))
    all_pixels.append(R)


storeAllImages = []

AverageR = (sum(all_pixels)/len(all_pixels))
print(AverageR)

storeAllImages.append(('GRK_image1.png',AverageR))
print(storeAllImages)

I would use skimage to load all the files at once using some pattern - in my case all the files are cars1.jpg, car2.jpg, etc so I use 'car*.jpg'

This gives a list of 3d arrays, and I can take the mean of the red channel (the first of the 3 dimensions) as a key to sorted with the reverse=True flag to go from most red to least.

You can view some of them to make sure it's working, then save them, using enumerate to label.

import numpy as np
import matplotlib.pyplot as plt
from skimage.io import imread_collection, imshow, imsave

images = sorted(imread_collection("car*.jpg", conserve_memory=False), 
                key=lambda x: np.mean(x[:,:,0]), 
                reverse=True)

# to view your work
for i in images:
    plt.figure()
    plt.imshow(i)

# save images starting with most red
for c, i in enumerate(images):
    imsave(f'most_red_{c}.jpg', i)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM