![](/img/trans.png)
[英]Understanding tf.extract_image_patches for extracting patches from an image
[英]Extract N number of patches from an image
我有一張尺寸為155 x 240
的圖像。 像下面這樣:
我想提取特定形狀的補丁(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)
假設您要省略的像素值為 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
您將獲得以下圖像:
這是主要邏輯,如果您希望更嚴格的界限,您應該正確調整切片。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.