因此,我尝试使用PIL和NumPy将图像转换为数组。然后,我尝试遍历文件并从中获取所有图像,然后查看它必须要多少个红色,绿色和蓝色像素才能看到图像的主要颜色,然后尝试这样做:
import numpy as np
import os
import time
from PIL import Image
def load_image(image: str):
img = Image.open(image)
img.load()
return img
def image_to_array(image):
array_img = np.asarray(image,dtype="int32")
return array_img
def get_image_color(image):
img = load_image(image)
img_array = image_to_array(img)
time.sleep(0.05)
red = 0
green = 0
blue = 0
for i in img_array:
for j in i:
if j[0] != j[1] != j[2]:
if j[0] > j[1] and j[0] > j[2]:
red += 1
elif j[1] > j[0] and j[1] > j[2]:
green += 1
elif j[2] > j[0] and j[2] > j[1]:
blue += 1
if red > green and red > blue:
return "Red Image"
elif green > red and green > blue:
return "Green Image"
elif blue > red and blue > green:
return "Blue Image"
def get_all_images(path: str):
images = os.listdir(path)
return images
PATH = "File's Path here"
red_images = get_all_images(f"{PATH}\\Red_Images\\")
green_images = get_all_images(f"{PATH}\\Green_Images\\")
blue_images = get_all_images(f"{PATH}\\Blue_Images\\")
for red_img in red_images:
print(red_img)
print(f"Picture: {red_img.split('.')[0]} =",get_image_color(f"{PATH}\\Red_Images\\{red_img}"))
当我通过for
循环运行它时,它会检测到第一张图像,但是第二张图像却遇到了索引错误
这是输出:
red_image1.jpg
Picture: red_image1 = Red Image
red_image2.jpg
Traceback (most recent call last):
File "ADD_PATH_HERE/color_from_image.py",line 57,in <module>
print(f"Picture: {red_img.split('.')[0]} =",get_image_color(f"
{PATH}\\Red_Images\\{red_img}"))
File "ADD_PATH_HERE/color_from_image.py",line 27,in get_image_color
if j[0] > j[1] and j[0] > j[2]:
IndexError: invalid index to scalar variable.