[英]Extract N number of patches from an image
I have an image of dimension 155 x 240
.我有一张尺寸为
155 x 240
的图像。 Like the following:像下面这样:
I want to extract certain shape of patchs (25 x 25)
.我想提取特定形状的补丁
(25 x 25)
。 I don't want to patch from the whole image .我不想修补整个图像。
I want to extract N number of patch from non-zero (not background) area of the image .我想从图像的非零(非背景)区域中提取N 个补丁。 How can I do that?
我怎样才能做到这一点? Any idea or suggestion or implementation will be appreciated.
任何想法或建议或实施将不胜感激。 You can try with either Matlab or Python.
您可以尝试使用 Matlab 或 Python。
Note: I have generated a random image so that you can process it for patching.注意:我生成了一个随机图像,以便您可以对其进行处理以进行修补。
image_process
variable is that image in this code. 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)
Lets assume that the pixels values you want to omit is 0.假设您要省略的像素值为 0。
In this case what you could do, is first find the indices of the non-zero values, then slice the image in the min
/ max
position to get only the desired area, and then simply apply extract_patches_2d
with the desired window size and number of patches.在这种情况下,您可以做的是首先找到非零值的索引,然后在
min
/ max
位置对图像进行切片以获得所需的区域,然后简单地应用具有所需窗口大小和数量的extract_patches_2d
补丁。
For example, given the dummy image you supplied:例如,给定您提供的虚拟图像:
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)
If you plot the only_desired_area
you will get the following image:如果您绘制
only_desired_area
您将获得以下图像:
This is the main logic if you wish an even tighter bound you should adjust the slicing properly.这是主要逻辑,如果您希望更严格的界限,您应该正确调整切片。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.