Patch Extracting In Python - python

I have an image and I would like to extract patches of it and then save each patch as an image in that folder. Here is my first attempt:
from sklearn.feature_extraction import image
from sklearn.feature_extraction.image import extract_patches_2d
import os, sys
from PIL import Image
imgFile = Image.open('D1.gif')
window_shape = (10, 10)
B = extract_patches_2d(imgFile, window_shape)
print imgFile
But I get the following error:
AttributeError: shape
I have searched through internet and I couldn't find anything. I would be very grateful if anyone can help me on this.
Thanks in advance

As per documentation first parameter for extract_patches_2d is an array or a shape.
You should first create an array from your imgFile so you get the pixels, and then pass that array to the function.
import numpy
import PIL
# Convert Image to array
img = PIL.Image.open("foo.jpg").convert("L")
arr = numpy.array(img)

Related

Python image library, Select random pictures from files

Hi I need some help with something I'm working on, I have this code that gets 2 pictures from 2 different folders and pastes it over each other creating 1 final merged image, what I want though is to merge two randomly selected pictures from the separate directories, thanks
from PIL import Image
import os
import random
import numpy as np
img1 = Image.open("/Users/Liam/Pictures/1/dfd.jpg").convert("RGBA")
img2 = Image.open("/Users/Liam/Pictures/2/face.png").convert("RGBA")
img1.paste(img2, (0,0), mask = img2)
img1.show()
It is actually pretty easy, check my example below
from PIL import Image
import os
import random
import numpy as np
basedir1 = "/Users/Liam/Pictures/1/"
basedir2 = "/Users/Liam/Pictures/2/"
first_image_list = os.listdir(basedir1)
second_image_list = os.listdir(basedir2)
img1 = Image.open(os.path.join(basedir1, random.choice(first_image_list))).convert("RGBA")
img2 = Image.open(os.path.join(basedir2, random.choice(second_image_list))).convert("RGBA")
img1.paste(img2, (0,0), mask = img2)
img1.show()

How do I generate a random colored image using Image.fromaray() in python?

I am trying to create a random image using NUMPY. First I am creating a random 3D array as it should be in the case of an image e.g. (177,284,3).
random_im = np.random.rand(177,284,3)
data = np.array(random_im)
print(data.shape)
Image.fromarray(data)
But when I am using Image.fromarray(random_array), this is throwing the following error.
Just to check if there is any issue with the shape of the array, I converted an image back to the array and converted it back after copying it to the other variable. And I got the output I was looking for.
img = np.array(Image.open('Sample_imgs/dog4.jpg'))
git = img.copy()
git.shape
Image.fromarray(git)
They both have the same shape, I don't understand where am I making the mistake.
When I am creating a 2D array and then converting it back it is giving me a black canvas of that size (even though the pixels should not be black).
random_im = np.random.randint(0,256,size=(231,177))
print(random_im)
# data = np.array(random_im)
print(data.shape)
Image.fromarray(random_im)
I was able to get this working with the solution detailed here:
import numpy as np
from PIL import Image
random_array = np.random.rand(177,284,3)
random_array = np.random.random_sample(random_array.shape) * 255
random_array = random_array.astype(np.uint8)
random_im = Image.fromarray(random_array)
random_im.show()
----EDIT
A more elegant way to get a random array of the correct type without conversions is like so:
import numpy as np
from PIL import Image
random_array = np.random.randint(low=0, high=255,size=(250,250),dtype=np.uint8)
random_im = Image.fromarray(random_array)
random_im.show()
Which is almost what you were doing in your solution, but you have to specify the dtype to be np.uint8:
random_im = np.random.randint(0,256,size=(231,177),dtype=np.uint8)

How to shuffle pixels in an image using Python Pillow?

My goal is to shuffle all pixels in a 512x512 Python Pillow image. Also, I need the time performance to be relatively good. What I've tried:
from PIL import Image
import numpy as np
orig = Image.open('img/input2.jpg')
orig_px = orig.getdata()
np_px = np.asarray(orig_px)
np.random.shuffle(np_px)
res = Image.fromarray(np_px.astype('uint8')).convert('RGB')
res.show()
The Preview app gives me the following error:
The file “tmp11g28d6z.PNG” could not be opened.
It may be damaged or use a file format that Preview doesn’t recognise.
I cannot figure out, what went wrong. I would be grateful for any suggestions about fixing this code or trying a different approach to solving this problem.
Main problem that getdata provide you 1d array, and fromarray requires 2d or 3d array. see corrected code. You maybe notice two reshapes. So first reshape make array of pixels. Each pixel has 3 values. Than shuffle them, than reshape in image. If you comment np.random.shuffle(orig_px) you will get original image as is.
from PIL import Image
import numpy as np
orig = Image.open('test.jpg')
orig_px = orig.getdata()
orig_px = np.reshape(orig_px, (orig.height * orig.width, 3))
np.random.shuffle(orig_px)
orig_px = np.reshape(orig_px, (orig.height, orig.width, 3))
res = Image.fromarray(orig_px.astype('uint8'))
res.save('out.jpg')

How to convert wand.image.Image to PIL.Image?

I spent whole day on this problem and did not see answer in stack overflow!
I tried this but did not work:
>> pil_image = Image.frombytes('RGBA', wand_image.size, wand_image.make_blob(format='png'), 'raw')
ValueError: not enough image data
I appreciate every solution.
This doesn't involve numpy:
pil_image = PIL.Image.open(io.BytesIO(wand_image.make_blob("png"))
This worked for me:
img_buffer = numpy.asarray(bytearray(wand_img.make_blob(format='png')), dtype='uint8')
bytesio = io.BytesIO(img_buffer)
pil_img = PIL.Image.open(bytesio)
one way is through numpy - meaning to export PIL image into numpy array and then read it by wand
from wand.image import Image
from IPython.display import display
with Image.from_array(np.array(img)) as ximg:
display(ximg)
or the other way around
from wand.image import Image
from matplotlib import cm
with Image(filename='rose:') as img:
array = np.array(img)
im = Image.fromarray(np.uint8(cm.gist_earth(array)*255))

To get image from cifat10-dataset

I am trying to get images from cifar10-dataset. When i rebuild image from array,
i see 9 same images in one picture, i don't know what is the problem.
When i load image from data, single_img shape (3072,). After that, i reshape
my single_img varible (32, 32, 3). I don't know where is the problem.
Here my code;
import cPickle
from PIL import Image
import numpy as np
f = open("/home/leo/Downloads/cifar-10-batches-py/data_batch_1", "rb")
tupled_data= cPickle.load(f)
f.close()
img = tupled_data['data']
single_img = np.array(img[0])
single_img_reshaped = single_img.reshape(32, 32 ,3)
j = Image.fromarray(single_img_reshaped)
j.save("/home/leo/Desktop/blabla.bmp")
Example image;
Be sure to be careful about the format of the pixel array of the image..
[R....G....B]
So you just change its format to
[[[R,G,B],....,[R,G,B]]
[[R,G,B],....,[R,G,B]]
[[R,G,B],....,[R,G,B]]]
But
single_img_reshaped = single_img.reshape(32, 32 ,3)
don't do it like before.

Categories