【发布时间】:2022-01-14 20:18:16
【问题描述】:
我有一个看起来像这样的图像(它被炸毁了,但每个正方形只有一个像素)。我希望能够计算每个黑色区域中的像素数。区域被定义为水平和垂直相邻的像素(不是对角线)。所以在这张图片中有四个。输出可以是某种字典,其中区域标识符(可能像质心)映射到该区域中的像素数,或者只是一个总数列表,如 [14,3,9,9]。
我似乎无法弄清楚如何让实际的像素数起作用。
另外,我能找到的最接近的是this question,但我仍然无法让它为我工作。
我在谷歌上搜索了 connectedComponentsWithStats 函数的工作原理。我尝试模糊图像和一切以摆脱可能的“对角线”连接。我假设它是我应该使用的那个,但也许有更好的东西?
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import cv2
d = [[9, 8, 9, 3, 2], [8, 7, 8, 9, 1], [9, 6, 5, 8, 9], [9, 7, 6, 7, 9], [9, 8, 7, 8, 9], [6, 9, 8, 9, 4], [5, 6, 9, 4, 3], [6, 7, 8, 9, 2], [7, 8, 9, 2, 1], [8, 9, 2, 1, 0]]
a = np.array([[0 if x < 9 else 255 for x in z] for z in d])
img = Image.fromarray(a.astype(np.uint8), mode='L')
img.save("test.jpg")
img = cv2.imread('test.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (1, 1), 0)
components, output, stats, centroids = cv2.connectedComponentsWithStats(blurred, connectivity = 4)
output
【问题讨论】:
-
不要模糊图像。只需将
connectivityInconnectedComponentsWithStats()更改为 4 而不是 8。
标签: python arrays image opencv image-processing