![](/img/trans.png)
[英]Tensorflow - Finding biggest 3 neighbor pixels for each pixel in an image tensor
[英]fastest way to select 7*7 neighbor pixels for every pixel in an image in Python
需要將圖像作為數組讀取,並為每個像素選擇7 * 7個相鄰像素,然后重新整形並作為第一行訓練集:
import numpy as np
from scipy import misc
face1=misc.imread('face1.jpg')
face1
尺寸為(288, 352, 3)
face1
(288, 352, 3)
,需要為每個像素找到7 * 7個相鄰像素,所以49 * 3顏色然后將其重新整形為(1,147)
數組並將其堆疊成所有像素的數組,我拿了以下方法:
X_training=np.zeros([1,147] ,dtype=np.uint8)
for i in range(3, face1.shape[0]-3):
for j in range(3, face1.shape[1]-3):
block=face1[i-3:i+4,j-3:j+4]
pxl=np.reshape(block,(1,147))
X_training=np.vstack((pxl,X_training))
得到的X_training
形狀是(97572, 147)
X_training
(97572, 147)
並且最后一行包含全部為零:
a = len(X_training)-1
X_training = X_training[:a]
上面的代碼適用於一張圖片,但Wall time: 5min 19s
我有2000張圖片,因此所有圖片都需要很Wall time: 5min 19s
。 我正在尋找一種更快的方法來迭代每個像素並執行上述任務。
一種有效的方法是使用stride_tricks
在圖像上創建一個滾動窗口,然后將其展平:
import numpy as np
face1 = np.arange(288*352*3).reshape(288, 352, 3) # toy data
n = 7 # neighborhood size
h, w, d = face1.shape
s = face1.strides
tmp = np.lib.stride_tricks.as_strided(face1, strides=s[:2] + s,
shape=(h - n + 1, w - n + 1, n, n, d))
X_training = tmp.reshape(-1, n**2 * d)
X_training = X_training[::-1] # to get the rows into same order as in the question
tmp
是圖像的5D視圖,其中tmp[x, y, :, :, c]
等效於顏色通道c
face1[x:x+n, y:y+n, c]
。
以下是我筆記本電腦上的<1s:
import scipy as sp
im = sp.rand(300, 300, 3)
size = 3
ij = sp.meshgrid(range(size, im.shape[0]-size), range(size, im.shape[1]-size))
i = ij[0].T.flatten()
j = ij[1].T.flatten()
N = len(i)
L = (2*size + 1)**2
X_training = sp.empty(shape=[N, 3*L])
for pixel in range(N):
si = (slice(i[pixel]-size, i[pixel]+size+1))
sj = (slice(j[pixel]-size, j[pixel]+size+1))
X_training[pixel, :] = im[si, sj, :].flatten()
X_training = X_training[-1::-1, :]
當我想不出單行矢量化版本時,我總是有點難過,但至少它對你來說更快。
使用scikit-image:
import numpy as np
from skimage import util
image = np.random.random((288, 352, 3))
windows = util.view_as_windows(image, (7, 7, 3))
out = windows.reshape(-1, 7 * 7 * 3)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.