Home > Net >  Pixel extraction with numpy
Pixel extraction with numpy

Time:11-26

hey i made this little script to cut a picture in 4 (get 4 pic, each a different corner of the source) but the files obtained are 2 with an half of the source and the 2 others are one (thin) strip of the source. wondering what i got wrong

import numpy as np;
from PIL import Image;
import imageio;
import math;


filename="preview_redd_it-8qwf04k4uc181.jpg"
im_in = Image.open(filename)
img = np.asarray(im_in)
filename=filename.removesuffix(".jpg")

print(img.shape)

shape= img.shape

maxX=math.floor(shape[0]/2)
maxY=math.floor(shape[1]/2)

shape=np.shape((maxX,maxY,shape[2]))
imagesList=[np.zeros(shape),np.zeros(shape),np.zeros(shape),np.zeros(shape)]

for i in range (0,4):
    xmin=(i%2)*maxX
    xmax=(i%2)*maxX maxX

    ymin=int(i/2)*maxY
    ymax=int(i/2)*maxY maxY

    print(str(xmin) ":" str(xmax))
    print(str(ymin) ":" str(ymax))
    print(" ")

    imagesList[i]=img[xmin:xmax][ymin:ymax]
    imageio.imsave(filename str(i) ".png",imagesList[i],'jpg')

the ouput:
enter image description here
(sorry for the eye cancer)

CodePudding user response:

If you want the four corners from the mid of each axis then you can use:

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

%matplotlib inline
pil_im = Image.open('lena1.jpg', 'r')
img = np.asarray(pil_im)
plt.imshow(img)
plt.show()

mid_0, mid_1 = img.shape[0]//2, img.shape[1]//2
plt.subplot(2, 2, 1)
plt.imshow(img[0:mid_0, 0:mid_1])
plt.subplot(2, 2, 2)
plt.imshow(img[0:mid_0, mid_1:])
plt.subplot(2, 2, 3)
plt.imshow(img[mid_0:, 0:mid_1])
plt.subplot(2, 2, 4)
plt.imshow(img[mid_0:, mid_1:])

plt.tight_layout()
plt.show()

output:

enter image description here

  • Related