首页 > 解决方案 > 使用python选择图像的区域

问题描述

我正在尝试选择图像的一个区域来对图像的特定区域进行一些分析。

但是,当我在网上搜索时,我只能找到有关如何选择矩形区域的指南。我需要选择一个使用鼠标绘制的区域。下文包括此类区域的一个示例。

任何人都可以向我推荐一些关键词或库来搜索以帮助我解决这个问题或链接到执行类似操作的指南吗?

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

我尝试选择的区域示例

标签: pythonimage-processingroi

解决方案


我根据这个答案制作了一个简单的工作示例。我也尝试过使用scipy.ndimage.morphology.fill_binary_holes,但无法让它工作。请注意,提供的函数需要更长的时间,因为它假设输入图像是灰度而不是二值化的。

我特别避免使用 OpenCV,因为我发现设置有点乏味,但我认为它也应该提供等效的(见这里)。

此外,我的“二值化”有点老套,但您可能会自己弄清楚如何将图像解析为有效格式(如果您在程序中生成结果可能会更容易)。在任何情况下,我建议确保您具有正确的图像格式,因为 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)

这会产生以下结果: 最后结果


推荐阅读