【发布时间】:2020-05-09 03:42:12
【问题描述】:
所以我尝试使用 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.
【问题讨论】:
-
你忘记了输出 ;) 在哪个 for 循环中?
-
在遍历 red_images 列表的 for 循环中
-
作为一般提示:使用 HSV 颜色空间而不是 RGB/BGR,如果您正在分析颜色,这通常会使事情变得更容易;)
-
那么你有什么尝试?例如,您是否打印了数组的大小?你能缩小错误发生的原因吗?哦,还有其他问题:如果您的图像碰巧拥有与蓝色像素一样多的红色、绿色和蓝色像素,会发生什么?
-
因此,如果所有像素都是相同的数字,它可能会打印“红色图像”,因为这是检查的第一种颜色,但我的问题是,当代码运行一次时,它会检测到图像的颜色很好,但是当它迭代到第二个图像时它会抛出 IndexError
标签: python arrays numpy python-imaging-library index-error