从图像中提取N个补丁

时间:2020-10-05 06:47:32

标签: python python-3.x matlab image-processing

我有一张尺寸为155 x 240的图片。如下所示:

Example of image

我想提取某些形状的补丁(25 x 25)我不想修补整个图像

我想从图像的非零(非背景)区域提取 N个补丁。我怎样才能做到这一点?任何想法,建议或实施将不胜感激。您可以尝试使用Matlab或Python。

注意: 我生成了一个随机图像,以便您可以对其进行修补。 image_process变量就是该代码中的图像。

import numpy as np
from scipy.ndimage.filters import convolve
import matplotlib.pyplot as plt

background = np.ones((155,240))
background[78,120] = 2
n_d = 50
y,x = np.ogrid[-n_d: n_d+1, -n_d: n_d+1]
mask = x**2+y**2 <= n_d**2
mask = 254*mask.astype(float)


image_process = convolve(background, mask)-sum(sum(mask))+1
image_process[image_process==1] = 0
image_process[image_process==255] = 1

plt.imshow(image_process)

1 个答案:

答案 0 :(得分:2)

让我们假设您要忽略的像素值为0。

在这种情况下,您可以做的是首先找到非零值的索引,然后将图像切成min / max的位置以仅获取所需的区域,然后只需将extract_patches_2d应用于所需的窗口大小和补丁数量即可。

例如,给定您提供的虚拟图像:

import numpy as np
from scipy.ndimage.filters import convolve
import matplotlib.pyplot as plt

background = np.ones((155,240))
background[78,120] = 2
n_d = 50
y,x = np.ogrid[-n_d: n_d+1, -n_d: n_d+1]
mask = x**2+y**2 <= n_d**2
mask = 254*mask.astype(float)


image_process = convolve(background, mask)-sum(sum(mask))+1
image_process[image_process==1] = 0
image_process[image_process==255] = 1
plt.figure()
plt.imshow(image_process)
plt.show()

from sklearn.feature_extraction.image import extract_patches_2d
x, y = np.nonzero(image_process)
xl,xr = x.min(),x.max()
yl,yr = y.min(),y.max()
only_desired_area = image_process[xl:xr+1, yl:yr+1]

window_shape = (25, 25)
B = extract_patches_2d(only_desired_area, window_shape, max_patches=100)  # B shape will be (100, 25, 25)

如果绘制only_desired_area,将得到以下图像: enter image description here

这是主要逻辑,如果您希望收紧边界,则应适当调整切片。