我正在尝试选择图像的一个区域来对图像的特定区域进行一些分析。
但是,当我在网上搜索时,我只能找到有关如何选择矩形区域的指南。我需要选择一个使用鼠标绘制的区域。下面是此类区域的示例。
是否有人可以向我推荐一些关键字或库来搜索以帮助我解决这个问题或指向执行类似操作的指南的链接?
另外,我不确定这是否是必要的信息,但我尝试对感兴趣区域进行的分析是找出该特定区域中白色像素与黑色像素的比例。
最佳答案
我根据 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)
关于python - 使用python选择图像的区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51720110/