我正在寻找使用 Python 实现以下目标的最佳方法:
期望输出
输出一个数组、列表、字典或类似的东西来捕捉这些主色值。
甚至可能是显示颜色的 Matplotlib 图(如像素艺术)。
我尝试了什么?
可以使用图像切片器对图像进行切片:
import image_slicer
image_slicer.slice('image_so_grid.png', 4)
然后,我可能会使用类似这样得到的平均颜色但是我相信有更好的方法来做到这一点。
使用 Python 执行此操作的最佳方法是什么?
这适用于 4 个部分,但您需要弄清楚如何使其适用于 'n' 个部分:
import cv2
img = cv2.imread('image.png')
def fourSectionAvgColor(image):
rows, cols, ch = image.shape
colsMid = int(cols/2)
rowsMid = int(rows/2)
numSections = 4
section0 = image[0:rowsMid, 0:colsMid]
section1 = image[0:rowsMid, colsMid:cols]
section2 = image[rowsMid: rows, 0:colsMid]
section3 = image[rowsMid:rows, colsMid:cols]
sectionsList = [section0, section1, section2, section3]
sectionAvgColorList = []
for i in sectionsList:
pixelSum = 0
yRows, xCols, chs = i.shape
pixelCount = yRows*xCols
totRed = 0
totBlue = 0
totGreen = 0
for x in range(xCols):
for y in range(yRows):
bgr = i[y,x]
b = bgr[0]
g = bgr[1]
r = bgr[2]
totBlue = totBlue+b
totGreen = totGreen+g
totRed = totRed+r
avgBlue = int(totBlue/pixelCount)
avgGreen = int(totGreen/pixelCount)
avgRed = int(totRed/pixelCount)
avgPixel = (avgBlue, avgGreen, avgRed)
sectionAvgColorList.append(avgPixel)
return sectionAvgColorList
print(fourSectionAvgColor(img))
cv2.waitKey(0)
cv2.destroyAllWindows()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句