图像上的网格以计算平均颜色

Grid on Image to compute the average color

您好,我已经对图像进行了边缘检测,现在我想计算图像中像素的平均颜色。首先,我需要将图像转换为 10x10 网格,其中每个网格元素代表单独的块。对于每个块,我需要计算平均颜色。有没有办法做到这一点?任何帮助表示赞赏。目前我可以在图像上绘制网格,但我无法从中进行计算。

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('images/0.jpg',0)
edges = cv2.Canny(img,100,200)

plt.subplot(122),plt.imshow(edges,cmap = 'gray')
plt.title('Edge Image'), plt.xticks([]), plt.yticks([])

plt.show()

一种方法是使用块平均调整图像大小。为此,必须计算新尺寸,使新图像中的每个像素代表原始图像中的 10x10 像素块。然后只需打印出调整大小的图像中的值列表。这些将是每个 10x10 块的平均颜色。

输入:

import cv2

img = cv2.imread('lena_crop.png')

# get shape
h, w, c = img.shape
print (h,w,c)


# compute scale size so that each pixel in the resize image corresponds to 10x10 original pixels
hs = round(h/10)
ws = round(w/10)
print(hs,ws)

# resize image using block averaging
resized = cv2.resize(img, (ws,hs), interpolation = cv2.INTER_AREA)

cv2.imshow("Resized image", resized)
cv2.waitKey(0)
cv2.destroyAllWindows()

print(list(resized))


我们从 250x250 大小的图片开始。新尺寸将为 25x25。结果的前几个值是:

[array([[112, 132, 225],
       [109, 132, 225],
       [111, 138, 231],
       [ 85,  69, 173],
       [ 83,  73, 178],
       [ 87,  83, 188],
       [ 93,  96, 204],
       [ 95,  99, 206],
       [ 97, 101, 210],
       [ 97, 101, 209],
       [ 99, 101, 206],
       [ 95,  99, 206],
       [ 97, 101, 208],
       [ 96,  98, 204],
       [ 96,  97, 203],
       [ 94,  89, 190],
       [101, 103, 201],
       [111, 132, 223],
       [107, 131, 224],
       [106, 129, 221],
       [133, 176, 237],
       [106, 117, 197],
       [ 94,  91, 189],
       [ 94,  93, 193],
       [ 93,  92, 193]], dtype=uint8), array([[110, 133, 228],
       [112, 140, 230],
       [105, 130, 227],
       [ 78,  67, 173],
       [ 80,  71, 178],
       [ 84,  80, 189],
       [ 91,  93, 203],
       [ 94,  96, 206],
       [ 95,  96, 209],
       [ 96,  97, 209],
       [ 90,  92, 206],
       [ 92,  93, 203],
       [ 98,  98, 205],
       [ 95,  96, 205],
       [ 92,  93, 205],
       [ 94,  90, 197],
       [ 97,  89, 191],
       [117, 132, 223],
       [110, 133, 225],
       [109, 129, 223],
       [110, 131, 220],
       [140, 185, 236],
       [ 92,  89, 187],
       [ 94,  91, 190],
       [ 72,  40, 118]], dtype=uint8), array([[111, 138, 231],
...