我正在尝试提取位于特定文件夹(“图像”)中的多个图像的特征。 我想使用 tabulate 包将此功能(灰度、R、G、B、alpha、高度和宽度)插入到表格中。 主要问题是迭代文件夹并提取单个红色、绿色、蓝色 channel 的平均值,并获取灰度值(如果该比例中存在图像)。之后,我想将所有信息插入表中。我无法执行任何此操作。 我已经尝试过这段代码,但它给了我很多像素值。 我想获得平均值,因此每个 channel 只有一个数字。 请问有人可以帮忙吗?
import os
import numpy as np
import cv2
for img in os.listdir(image_path):
img = cv2.imread(os.path.join(image_path, img))
r,g,b = cv2.split(img)
rgb_img = cv2.merge((r,g,b))
x,y,z = np.shape(img)
red = np.zeros((x,y,z),dtype=int)
green = np.zeros((x,y,z),dtype=int)
blue = np.zeros((x,y,z),dtype=int)
for i in range(0,x):
for j in range(0,y):
red[i][j][0] = rgb_img[i][j][0]
green[i][j][1]= rgb_img[i][j][1]
blue[i][j][2] = rgb_img[i][j][2]
我不知道还有什么方法,有人可以推荐吗?我真的很感激。 谢谢
最佳答案
如果您想要 channel (R、G、B)的平均值,并最终希望使用制表将其存储在表格中,您可以执行以下操作:
我将使用 OpenCV(加载图像)和 numpy(因为为什么不)
import cv2
import numpy as np
import os
from tabulate import tabulate
images = os.listdir('./Test')
num_images = len(images)
data = [] # using an array is more convenient for tabulate.
for i in range(num_images):
img = cv2.imread('./Test/' + images[i])
avgR = np.mean(img[:,:,2])
avgG = np.mean(img[:,:,1])
avgB = np.mean(img[:,:,0])
data.append([images[i], avgR, avgG, avgB])
print(tabulate(data, headers=['img_name','R', 'G', 'B'], tablefmt='fancy_grid'))
'''
╒════════════╤══════════╤══════════╤══════════╕
│ img_name │ R │ G │ B │
╞════════════╪══════════╪══════════╪══════════╡
│ test1.jpg │ 49.3213 │ 112.408 │ 145.949 │
├────────────┼──────────┼──────────┼──────────┤
│ test2.jpeg │ 93.0038 │ 94.4466 │ 95.0824 │
├────────────┼──────────┼──────────┼──────────┤
│ test3.jpg │ 100.181 │ 71.6575 │ 66.4233 │
╘════════════╧══════════╧══════════╧══════════╛
'''
这是我的目录结构:
该代码位于电影抓取器目录中。因此我使用了路径“./Test”。点“.”代表当前目录。
关于python - 如何用Numpy Python获取多张图像的RGB单 channel 平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65467880/