我有一個看起來像這樣的影像(它被放大了,但每個方塊只有一個像素)。我希望能夠計算每個黑色區域的像素數。區域被定義為水平和垂直相鄰的像素(不是對角線)。所以在這張圖片中有四個。輸出可以是某種帶有區域識別符號(如質心)映射到該區域中的像素數的字典,或者只是像 [14, 3, 9, 9] 這樣的總數串列就可以了。
我似乎無法弄清楚如何讓實際的像素數起作用。
此外,我能找到的最接近的是這個問題,但我仍然無法讓它為我作業。
我在谷歌上搜索了 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
uj5u.com熱心網友回復:
connectedComponentsWithStats 已經給你area,這是可以在圖片中找到的每個組件(非零像素)中的像素數。
a = np.where(np.array(d) < 9, 255, 0).astype(np.uint8)
(nlabels, labels, stats, centroids) = cv.connectedComponentsWithStats(a, connectivity=4)
assert nlabels == 5 # = background 4 components
print(stats[:, cv.CC_STAT_AREA]) # area: array([15, 14, 3, 9, 9], dtype=int32)
注意Beaker 的評論:CC 有一個連接引數,您應該將其設定為“4-way”。
您應該反轉圖片,使黑色像素變為白色。white is non-zero 是真的,這總是前景,這是 CC 呼叫期望使用的。
檔案:https : //docs.opencv.org/3.4/d3/dc0/group__imgproc__shape.html#gac7099124c0390051c6970a987e7dc5c5
高斯模糊會將任何二值化影像變成灰度值的湯。不要應用高斯模糊,或者如果你需要它,然后閾值。connectedComponents* 將威脅任何非零 (!) 像素作為前景
uj5u.com熱心網友回復:
如果你想計算像素,OpenCV 有一個函式:cv2.countNonZero. 這會計算白色像素,但您可以通過首先計算影像高度和寬度來輕松計算黑色像素。
您的代碼將被修改如下:
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')
# Display image:
cv2.imshow("Image", img)
cv2.waitKey(0)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (1, 1), 0)
# Count number of white pixels:
whitePixels = cv2.countNonZero(blurred)
print("White pixels: " str(whitePixels))
# Get image height and width:
(imgHeight, imgWidth) = blurred.shape[:2]
# Get number of black pixels:
blackPixels = imgHeight*imgWidth - whitePixels
print("Black pixels: " str(blackPixels))
哪個列印:
White pixels: 34
Black pixels: 16
專業提示:不要使用jpg影像格式,它是有損的 - 它會壓縮和修改像素值。使用無損格式,例如png.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/380446.html
上一篇:學點實用SQL技巧題 ——《尋找面試候選人》LeetCode Plus 會員專享題【詳細決議】Hive / MySQL
