python - 如何解决每当我尝试查找多个图像的平均 RGB 值时发生的这个轴错误
问题描述
我一直在创建一个程序,它将以列表的形式返回存储在文件夹中的所有图像的平均 RGB 值。
我已经编写了代码来查找单个图像的平均 RGB 值,如下所示。
import cv2
import numpy as np
myimg2 = cv2.imread('/Users/farzeent.farooqui/Desktop/colors.jpg')
avg_color = np.array(myimg2).mean(axis=(0,1))
avg_rgb = avg_color[::-1]
print(avg_rgb)
然后我使用 for 循环来获取所有图像的 RGB 值
import cv2
import numpy as np
import os
def test():
path_of_images = "/Users/farzeent.farooqui/Frames"
list_of_images = os.listdir(path_of_images)
for image in list_of_images:
myimg2 = cv2.imread(os.path.join(path_of_images, image) )
avg_color = np.array(myimg2).mean(axis=(0,1))
avg_rgb = avg_color[::-1]
print(avg_rgb)
test()
但是当我尝试运行程序时,我不断收到以下错误:
---------------------------------------------------------------------------
AxisError Traceback (most recent call last)
<ipython-input-124-fbd55f77ab7c> in <module>
----> 1 test()
<ipython-input-123-ed7d4e9de700> in test()
10
11 myimg2 = cv2.imread(os.path.join(path_of_images, image) )
---> 12 avg_color = np.array(myimg2).mean(axis=(0,1))
13 avg_rgb = avg_color[::-1]
14 print(avg_rgb)
~/opt/anaconda3/lib/python3.8/site-packages/numpy/core/_methods.py in _mean(a, axis, dtype, out, keepdims, where)
164 is_float16_result = False
165
--> 166 rcount = _count_reduce_items(arr, axis, keepdims=keepdims, where=where)
167 if rcount == 0 if where is True else umr_any(rcount == 0):
168 warnings.warn("Mean of empty slice.", RuntimeWarning, stacklevel=2)
~/opt/anaconda3/lib/python3.8/site-packages/numpy/core/_methods.py in _count_reduce_items(arr, axis, keepdims, where)
73 items = nt.intp(1)
74 for ax in axis:
---> 75 items *= arr.shape[mu.normalize_axis_index(ax, arr.ndim)]
76 else:
77 # TODO: Optimize case when `where` is broadcast along a non-reduction
AxisError: axis 0 is out of bounds for array of dimension 0
解决方案
正如@burglarhobbit 在评论中指出的那样,您的目录可能包含非图像文件,这会导致您的代码抛出错误。
下面的代码将帮助您在特定目录中查找具有已知图像文件扩展名的文件。
from os import path, walk
def get_image_files(directory_of_images):
"""
This function is designed to traverse a directory tree and extract all
the image names contained in the directory.
:param directory_of_images: the name of the target directory containing
the images to be trained on.
:return: list of images to be processed.
"""
images_to_process = []
accepted_extensions = ('.bmp', '.gif', '.jpg', '.jpeg', '.png', '.svg', '.tiff')
for (dirpath, dirnames, filenames) in walk(directory_of_images):
for filename in filenames:
if filename.endswith(accepted_extensions):
images_to_process.append(path.join(dirpath, filename))
return images_to_process
list_of_images = get_image_files('/Users/user_name/Python_Projects/scratch_pad')
for image_to_process in list_of_images:
myimg2 = cv2.imread(image_to_process)
avg_color = np.array(myimg2).mean(axis=(0, 1))
avg_rgb = avg_color[::-1]
print(avg_rgb)
# output
[239.08779842 239.08779842 239.08779842]
[186.64632099 163.64886914 150.54838519]
推荐阅读
- websocket - 托管服务器端 Blazor 应用程序时 SignalR 出现问题
- angular - Angular 渲染 FormArray,在一页中包含 10k+ 行(每行 15 列)数据
- javascript - 单击多个图像可同时播放多个音频
- google-kubernetes-engine - 在 GKE 上使用 Istio 获取 Envoy 访问日志
- python - 在 Python 中嵌套时展平元组
- angular - ngbTooltip 不适用于动态创建的元素
- java - 如果按钮空闲,如何启动线程?
- java - 在 Java 中创建 UDF 以将一个数据框列映射到另一列
- java - 尝试在 Spoj 中提出问题,我编写的代码被接受,但显示内存使用为 4468mb。是什么导致如此高的内存使用率?
- sendgrid - 通过带有“&”的 sendgrid 发送模板电子邮件时发出警告