检测白像素密度低的区域

问题描述 投票:0回答:1

我是一名学生试图分析二进制图像,其中几乎整个图像是黑色的,但在图像中均匀分布了一些白色像素。我想检测整个图像是否具有均匀的白色像素密度。如果图像中的区域具有低密度的白色像素,我想检测它。

在下图中,我标记了一个没有白色像素的区域作为我想要检测的示例:

在我的程序中,我在制作图片之前得到了白色像素的坐标。然后我创建一个黑色BufferedImage并在每个坐标上写一个白色像素来创建我附加的图像。对我来说,最重要的是检测图像是否包含大于可调大小的完全黑色区域(我必须尝试找到正确的设置)

如果可以通过使用白色像素的坐标(不创建黑色图像然后添加所有白色像素)以良好的方式检测到这一点,那么我也会感兴趣。

我在我的程序中使用Java和OpenCV,有没有人对如何继续这样做有任何建议? OpenCV中是否有任何功能可以帮助我?

感谢所有答案

java opencv pixel
1个回答
0
投票

这是解决这个问题的粗略方法。我使用python解决了这个问题,但所有相同的规则都适用于Java。

我首先得到一组测试点,它有一个差距和一些随机性。

w, h = 1000, 1000
spacing = 25
blast_size = 100


def distance(p1, p2):
    return math.sqrt(math.pow(p1[0] - p2[0], 2) + math.pow(p1[1] - p2[1], 2))


def keep_point(p):
    if p[0] < 0 or p[0] >= w or p[1] < 0 or p[1] >= h:
        return False
    d = distance(p, (w/2, h/2))
    if d > blast_size:
        return True
    return False


grid = [
    (i + random.randint(-spacing, spacing), j + random.randint(-spacing, spacing))
    for i in range(spacing, w, spacing*2)
    for j in range(spacing, h, spacing*2)
]
grid = list(filter(keep_point, grid))


initial = np.zeros((h, w), np.uint8)
for i, j in grid:
    image[i, j] = 255

cv2.imshow("Initial", initial)
cv2.waitKey()

enter image description here

接下来,我计算每个点与邻居的最小距离。最大的最小距离将用作我们卷积的半径。卷积完成后,差距将非常明显。为了在卷积后获得间隙的中心,我采用轮廓的平均值。如果您可以有多个间隙,那么此时您需要进行斑点检测。

# Don't include self as a neighbor
def distance_non_equal(p1, p2):
    if p1 == p2:
        return float('inf')
    return distance(p1, p2)


min_distance = [
    min(map(lambda p2: distance_non_equal(p1, p2), grid))
    for p1 in grid
]

radius = int(max(min_distance))

kernel = np.zeros((2*radius+1, 2*radius+1), np.uint8)
y,x = np.ogrid[-radius:radius+1, -radius:radius+1]
mask = x**2 + y**2 <= radius**2
kernel[mask] = 255

convolution = cv2.filter2D(image, cv2.CV_8U, kernel)

contours = cv2.findContours(convolution, 0, 2)
avg = np.mean(contours[0],axis=1)
x = int(round(avg[0,0,0]))
y = int(round(avg[0,0,1]))

convolution[x, y] = 255
cv2.imshow("Convolution", convolution)
cv2.waitKey()

enter image description here

既然我们有差距的中心,我们可以近似边界。这是用于检测边界的非常粗略的算法。我根据它们与中心点的角度将点分成区域。对于每个区域,我将最近的点计为边界的一部分。最后,我对边框点的颜色不同。

def get_angle(p):
    angle = math.degrees(math.atan2(y - p[1], x - p[0]))
    if angle < 0:
        angle += 360
    return angle

angles = list(map(get_angle, grid))
zones = [
    [
        p
        for angle, p in zip(angles, grid)
        if i < angle < i + 360//12
    ]
    for i in range(0,360,360//12)
]

closest = [
    min(zone, key=lambda p2: distance((x,y), p2))
    for zone in zones
]

final = np.zeros((h, w, 3), np.uint8)
for i, j in grid:
    final[i, j] = [100,100,100]
for i, j in closest:
    final[i, j] = [255,255,255]

cv2.imshow("final", final)
cv2.waitKey()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.