algorithm - Slicing ndarray using floats in Python -


i want construct algorithm in python slice image n-by-n equal blocks. aware of existing python packages can this, interested in performing mathematical computations using dimensions of resulting blocks, need not integer values.

i have converted image input ndarray using numpy , cv2. curious if can slice ndarray object in way when split "pixel", take weighted average of "pixel's" contribution respective block.

for example, if image input have dimensions 100px x 100px, , want split image 7x7 blocks, since 100/7 = ~14.2857, each block have dimensions 14.2857 x 14.2857. doesn't make sense have fraction of pixel. instead, wish interpret first block contains of information pixels (1,1),(1,2),...,(1,14),(2,1),...,(3,1),...,(14,1),... ,(14,14), 0.2857 of pixels satisfying (15,k) , (k,15), , 0.2857*0.2857 pixel (15,15). wish 49 blocks.

any insight appreciated! thanks.

as correctly observed, cannot have 14.29 pixel in image. can perform downsampling 14 (or less) pixels or upsampling 15 (or more) pixels. think former intend, latter viable option too.

an easy approach resize image new size split 7x7. if use correct function (e.g. scipy.ndimage.interpolation.zoom) automatically interpolate pixel values.

for simplicity let's assume want split 5x5 image 2x2 blocks:

from scipy.ndimage.interpolation import zoom import numpy np  blocks = (2, 2)  image = np.arange(25).reshape(5, 5) * 10 print(image) # [[  0  10  20  30  40] #  [ 50  60  70  80  90] #  [100 110 120 130 140] #  [150 160 170 180 190] #  [200 210 220 230 240]]  # use np.ceil instead of np.floor upsampling zoom_factor = [np.floor(s / b) * b / s s, b in zip(image.shape, blocks)]  zoomed = zoom(image, zoom_factor) print(zoomed) # [[  0  14  26  40] #  [ 69  83  95 109] #  [131 145 157 171] #  [200 214 226 240]]  b1 in range(0, zoomed.shape[0], blocks[0]):     b2 in range(0, zoomed.shape[1], blocks[1]):         print('block:')         print(zoomed[b1:b1+blocks[0], :][:, b2:b2+blocks[1]]) # block: # [[ 0 14] #  [69 83]] # block: # [[ 26  40] #  [ 95 109]] # block: # [[131 145] #  [200 214]] # block: # [[157 171] #  [226 240]] 

note in zoomed image second pixel in first row has value of 14, contains contributions both neigbors 10 , 20. (it contains contribution other pixels because zoom uses default order 3 spline interpolation). other pixels in middle of image contain contribution entire surrounding neigborhood.


Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -