使用 Python 选择图像区域

4

我想选择图像的某个区域并对该区域进行一些分析。

然而,当我在网上搜索时,我只能找到关于如何选择矩形区域的指南。我需要选择使用鼠标绘制的区域。下面包括这种区域的示例。

是否有人能够向我推荐一些关键字或库来帮助我解决这个问题,或者提供类似操作的指南链接?

此外,我不确定这是否是必要信息,但我正在尝试对感兴趣的区域进行分析,以查找该特定区域中白色像素与黑色像素的比率。

Example of an area I am trying to select


这个区域总是完全封闭的吗?即,图像的8邻域中是否至少连接了一个像素? - dennlinger
@dennlinger 它将始终完全封闭。我不太确定您在第二个问题中的意思,但是这个ROI位于图像中央。谢谢! - Ruven Guna
8邻域指的是像素周围的八个相邻像素(左、左上、上、右上、右、右下、下、左下),而不是4邻域(左、上、右、下)。 - dennlinger
@dennlinger 我想我明白你的意思了。是的,在图像的8邻域中至少有一个像素相连。谢谢。 - Ruven Guna
1个回答

1
我基于this answer制作了一个简单的工作示例。我还尝试使用scipy.ndimage.morphology.fill_binary_holes,但无法使其工作。请注意,提供的函数需要更长的时间,因为它假定输入图像是灰度的而不是二值化的。

我特别避免使用OpenCV,因为我觉得设置有点繁琐,但我认为它也应该提供等效的功能(见此处)。

此外,我的“二值化”有点hacky,但您可能可以自己解析图像以获得有效格式(如果在程序中生成结果可能会更容易)。无论如何,建议确保您拥有适当的图像格式,因为jpeg的压缩可能会违反您的连通性,并在某些情况下导致问题。

import scipy as sp
import numpy as np
import scipy.ndimage
import matplotlib.pyplot as plt

def flood_fill(test_array,h_max=255):
    input_array = np.copy(test_array) 
    el = sp.ndimage.generate_binary_structure(2,2).astype(np.int)
    inside_mask = sp.ndimage.binary_erosion(~np.isnan(input_array), structure=el)
    output_array = np.copy(input_array)
    output_array[inside_mask]=h_max
    output_old_array = np.copy(input_array)
    output_old_array.fill(0)   
    el = sp.ndimage.generate_binary_structure(2,1).astype(np.int)
    while not np.array_equal(output_old_array, output_array):
        output_old_array = np.copy(output_array)
        output_array = np.maximum(input_array,sp.ndimage.grey_erosion(output_array, size=(3,3), footprint=el))
    return output_array

x = plt.imread("test.jpg")
# "convert" to grayscale and invert
binary = 255-x[:,:,0]

filled = flood_fill(binary)

plt.imshow(filled)

这将产生以下结果: final result


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接