how to resize cifar10 image from 32x32 to 227x227? - python

I have read the image from cifar-10-batches-python
import os
import numpy as np
from PIL import Image
from pylab import *
import matplotlib.pyplot as plt
from scipy.misc import imresize
# read data
data_dir = "F:\\dataSet\\cifar-10-batches-py"
testdata_dir="F:\\dataSet\\cifar-10-batches-py\\test_batch"
da=np.load(testdata_dir)
testdata=da['data']
testlabel=np.array(da['labels'])
train=np.empty((50000,3072))
label=np.empty((50000,))
for i in range(1,2):
str='data_batch_'+np.str(i)
path1=os.path.join(data_dir,str)
data=np.load(path1)
train[10000*(i-1):10000*i,:]=data['data']
label[10000*(i-1):10000*i,]=data['labels']
def intlabel(label):
for i in range(label.shape[0]):
label[i,]=int(float(label[i,]))
return label
def intdata(data):
n=data.shape[0]
for i in range(n):
for j in range(3072):
data[i,j]=int(float(data[i,j]))
return data
label,train=intlabel(label),intdata(train)
train,label=np.array(train),np.array(label)
train = train.reshape(train.shape[0], 3, 32,32)
train = train.astype('float32')
then I don't know how to resize the data.
I used the imreszie function to resize image, but the effect was not good

You can use opencv to pre-process the images-
import cv2
img = cv2.imread('IMAGE_LOCATION')
img_fin = cv2.resize(img, (227, 227))

Related

how to keep 3d or matrix like grid after calculating the mean for a list of images in python

##This is how I uploaded the list of images
import cv2
import numpy as np
from matplotlib.image import imread
import matplotlib.pyplot as plt
from skimage import color
import os, subprocess, glob, re
from PIL import Image
import glob
import numpy
##this upload data as 11x480x600 shape
list_images = []
for img in glob.glob('../proj/*.jpg'):
ims = cv2.imread(os.path.join(img))
list_images.append(ims)
im_arr = numpy.array(list_images)
im_gry = color.rgb2gray(im_arr)
##this code calculates the mean for all images
##but it returns 2d as 480x600
##I need to keep it as 3d or matrix-like
m_df = im_gry.mean(axis=0)
##I need to change 3d (1x480x600) into 1d list
##for further processing
##but this does not work as
##m_df.shape[2] is missing
image_shape=m_df[0].shape
frames_reshaped = m_df.reshape([
m_df.shape[0]*
m_df.shape[1],m_df.shape[2]])
frames_reshaped.shape

Python invert colors

I need to invert the colors of an image in Python using PIL, the problem is that I only have to invert the colors of the right half of the image and I don't know how to do it. Here is an example of how the image should look like.
And here is the code I made, bot it invert the colors of all the image.
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import PIL.ImageOps
image_file = Image.open("Abbildung1.jpg")
image_file.load()
image_data = np.asarray(image_file, dtype=np.uint8)
inverted_image = PIL.ImageOps.invert(image_file)
inverted_image.save("neuesBild.jpg")
You can use numpy to make two parts of the image then apply the transformation and finally combine it.
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import PIL.ImageOps
image_file = Image.open("some_image.jpeg")
image_file.load()
image_data = np.asarray(image_file, dtype=np.uint8)
width = image_data.shape[1]
left_half = image_data[:,0:width//2, :]
right_half = image_data[:,width//2:, :]
inverted_image_right = np.asarray(PIL.ImageOps.invert(Image.fromarray(right_half)))
total_image = np.hstack((left_half, inverted_image_right))
inverted_image = Image.fromarray(total_image)
inverted_image.save("invertion_half.jpeg")
That's it:
from PIL import Image
import PIL.ImageOps
img = Image.open('img.png').convert('RGB')
img.paste(ImageOps.invert(img.crop((img.width/2,0,img.width,img.height))),box=(int(img.width/2),0))
We have croped, inverted and pasted this croped-inverted image back.
Then you can check:
img.show()

I faced some problems to enhance on multiple images using Python, It shows some error

Here, I want to change the default sharpness of the image dataset. It works fine for a single image, but when I apply on multiple images, it shows me an error like AttributeError: 'numpy.ndarray' object has no attribute 'filter'. What should I do to fix this? To that end, my code is given below-
from PIL import Image
from PIL import ImageEnhance
import cv2
import glob
dataset = glob.glob('input/*.png')
other_dir = 'output/'
for img_id, img_path in enumerate(dataset):
img = cv2.imread(img_path,0)
enhancer = ImageEnhance.Sharpness(img)
enhanced_im = enhancer.enhance(8.0)
cl2 = cv2.resize(enhanced_im, (1024,1024), interpolation = cv2.INTER_CUBIC)
cv2.imwrite(f'{other_dir}/enhanced_{img_id}.png',cl2)
You're trying to use PIL to enhance a numpy array. cv2 converts images from image paths into numpy arrays. This doesn't work with PIL image operations.
You can load the image using PIL, do the PIL enhancements then convert it to a numpy array to pass into your cv2.resize() method.
Try:
from PIL import Image
from PIL import ImageEnhance
import cv2
import glob
import numpy as np
dataset = glob.glob('input/*.png')
other_dir = 'output/'
for img_id, img_path in enumerate(dataset):
img = Image.open(img_path) # this is a PIL image
enhancer = ImageEnhance.Sharpness(img) # PIL wants its own image format here
enhanced_im = enhancer.enhance(8.0) # and here
enhanced_cv_im = np.array(enhanced_im) # cv2 wants a numpy array
cl2 = cv2.resize(enhanced_cv_im, (1024,1024), interpolation = cv2.INTER_CUBIC)
cv2.imwrite(f'{other_dir}/enhanced_{img_id}.png',cl2)

vectorize, reshape, and normalise my image to image like mnist.train.images

How can I vectorize, reshape, and normalise my image to the same as the size vector of one of the images in mnist.train.images? I've tried the below so far with no success:
import os
import re
import numpy as np
import tensorflow as tf
from tensorflow.python.framework import ops
import os,sys
#import Image
from PIL import Image
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
# Load data and check the shape of the first mnist.train.images image
data_dir = 'temp'
mnist = read_data_sets(data_dir)
print("tmnist.train.images[0].shape is")
print(mnist.train.images[0].shape) # the result is (784,)
def resize_image(image):
img = Image.open(image)
arr = np.array(img)
#my mind is drawing a blank... additional code to make this work...
return arr
resize_image("test.png")
The following should work:
def resize_image(image):
img = Image.open(image)
img = img.resize((28, 28))
arr = np.array(img)
#convert to gray scale
if len(arr.shape) > 2:
arr = np.mean(arr, 2)
#flatten
arr = arr.flatten()
return arr

Split image and compare each parts

I'm trying to divide an image into n equal parts and then compare each blocks to define an "equilibrium" in illustrations.
For example in the image shown below the bottom tends to be similar compared to the top.
I've written this but I got stuck and don't know what to do, any help?
import math
import io
import numpy as np
from sklearn.cluster import KMeans
from PIL import Image
import image_slicer
from scipy import sum, average
tiles = image_slicer.slice('img/eq1.jpg', 2, save=False)
vectors = []
for tile in tiles:
image = tile.image
image = image.convert('RGB')
colors = np.array(image).tolist()
colors = [average(x, -1) for x in colors][0]
vectors.append(colors)
#lista = np.array(tile.image)
#print np.array(tile.image)
image.show()
from sklearn.metrics.pairwise import cosine_similarity
print cosine_similarity(vectors)
okay i kind of solved it writing this:
import math
import io
import numpy as np
from sklearn.cluster import KMeans
from PIL import Image
import image_slicer
from scipy import sum, average
from scipy.linalg import norm
import sklearn.metrics.pairwise
tiles = image_slicer.slice('img/ad.jpg', 4, save=False)
vectors = []
for tile in tiles:
image = tile.image
image = image.convert('RGB')
colors = np.array(image).tolist()
colors = [average(x, -1) for x in colors][0]
vectors.append(colors)
#lista = np.array(tile.image)
#print np.array(tile.image)
# image.show()
from sklearn.metrics.pairwise import cosine_similarity
print np.around(sklearn.metrics.pairwise.manhattan_distances(vectors))

Categories

Resources