【问题标题】:Using python to select an area of an Image使用python选择图像的区域
【发布时间】:2018-08-07 15:07:40
【问题描述】:

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

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

有人可以向我推荐一些关键词或库来搜索以帮助我解决此问题,或者指向执行类似操作的指南的链接吗?

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

【问题讨论】:

  • 这总是一个完全封闭的区域吗?即,图像的 8 邻域中是否至少有一个像素相连?
  • @dennlinger 它始终是完全封闭的。我不太清楚第二个问题是什么意思,但这个 ROI 位于图像的中间。谢谢!
  • 8-neighborhood 简单地指定一个像素的周围像素(左、左上、上、右上、右、右下、下、左下),而不是 4 -neighborhood(左、上、右、下)。
  • @dennlinger 我想我明白你的意思。是的,图像的 8 邻域中至少有一个像素相连。谢谢。

标签: python image-processing roi


【解决方案1】:

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

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

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

这会产生以下结果:

【讨论】:

    猜你喜欢
    • 2013-01-10
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    • 2015-02-20
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多