简体   繁体   English

如何使用 python PIL 中的平均像素之一对图像进行排序

[英]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.我正在使用 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.图像均为 640 x 480 RBG 格式。 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?我有 10 张图像(从 GRK_image1 到 GRK_image10),而不是输入 10 次以下的代码,有没有更快的方法可以一步循环遍历所有 10 张图像并获得每张图像的所有平均红色值? 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'我会使用 skimage 使用某种模式一次加载所有文件 - 在我的情况下,所有文件都是 car1.jpg、car2.jpg 等,所以我使用'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.这给出了 3d arrays 的列表,我可以将红色通道的平均值(3 个维度中的第一个)作为关键字,使用reverse=True标志从大多数sorted到 Z34D1F91FB2E514B85676FAB1A75A8。

You can view some of them to make sure it's working, then save them, using enumerate to label.您可以查看其中一些以确保其正常工作,然后使用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)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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