python - 在图像上网格以计算平均颜色

标签 python opencv computer-vision grid edge-detection

嗨,我已经对图像进行了边缘检测,现在我想计算图像中像素的平均颜色。首先,我需要将图像转换为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块的平均颜色。

输入:

enter image description here

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],
...

关于python - 在图像上网格以计算平均颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58178208/

相关文章:

machine-learning - 根据相似度对图像进行聚类

python - 在 python 中加载图像进行处理的最快方法

python - cv2.waitkey() 中的不同值是什么意思?

python - 如何在 linux 终端控制台中运行 python 脚本并继续使用命令行?

python - Pygame 按键不使用大写字母

python - 如何从打印消息并关闭程序的函数创建单元测试?

c++ - 如何构建使用 OpenCV 的 XCode 6 iOS 应用程序 - 未定义错误 __cplusplus

python - 如何在不同的机器上设置 celery worker ?

Python 类型错误 : UMat() missing required argument 'ranges' (pos 2)

c++ - 如何计算图像的分辨率?