when resizing a image set only resizing one image - image

When I was trying to resize an image set, it was only resizing the first image.How to resize all images? This is my code:
import numpy as np
import os
import cv2
pic_num = 1
img = cv2.imread("E:\ele/"+str(pic_num)+'.jpg',cv2.IMREAD_GRAYSCALE)
resized_image = cv2.resize(img,(100,100))
cv2.imwrite("E:\eye/"+str(pic_num)+'.jpg',resized_image)
pic_num += 1

If you are just looping through files and change it, and don't worried about time.
then you can just use for loop in python
For example you have pics from 1 too 100
Then you can just do following:
import numpy as np
import os
import cv2
for pic_num in range(1,100):
img = cv2.imread("E:\ele/"+str(pic_num)+'.jpg',cv2.IMREAD_GRAYSCALE)
resized_image = cv2.resize(img,(100,100))
cv2.imwrite("E:\eye/"+str(pic_num)+'.jpg',resized_image)

Related

How to convert numpy array into image using PIL?

The following code gives me black images and I can't understand why:
Imports:
import numpy as np
from PIL import Image
Code:
arr2 = np.zeros((200,200), dtype=int)
arr2[80:120,80:120]=1
im = Image.fromarray(arr2,mode="1")
im.save("C:/Users/Admin/Desktop/testImage.jpg")
I think you want something more like this, using Boolean True and False:
import numpy as np
from PIL import Image
# Create black 1-bit array
arr2 = np.full((200,200), False, dtype=bool)
# Set some bits white
arr2[80:120,80:120]=True
im = Image.fromarray(arr2)
im.save('a.png')
print(im)
<PIL.Image.Image image mode=1 size=200x200 at 0x103FF2770>

How to generate a matplotlib animation using an image array?

So my problem is generating an animation from the list img_array. The code above that is basically used to get an image from the folder, annotate it and then save it into the array. Was wondering if anyone would have any suggestions on how to convert the images in the image array into an animation. Any help is appreciated! TIA.
I tried FFmepg and what not but none of them seem to work. I also tried videowriter in OpenCV but when I tried to open the file I get that this file type is not supported or corrupt.
import cv2
import numpy as np
import glob
import matplotlib.pyplot as plt
from skimage import io
import trackpy as tp
import pims
import pylab as pl
##########
pixel_min=23
min_mass=5000
Selector1=[1,2,3,4,5,6,7,11]
##########
frames = pims.ImageSequence('/Users/User/Desktop/eleventh_trial_2/*.tif', as_grey=True)
f1 = tp.locate(frames[0], pixel_min,minmass=min_mass)
plt.figure(1)
ax3=tp.annotate(f1,frames[0])
ax = plt.subplot()
ax.hist(f1['mass'], bins=20)
ax.set(xlabel='mass', ylabel='count');
f = tp.batch(frames[:], pixel_min, minmass=min_mass);
#f = tp.batch(frames[lower_frame:upper_frame], pixel, minmass=min_mass);
t=tp.link_df(f,10,memory=3)
##############
min_mass=8000#12000 #3000#2000 #6000#3000
pixel_min=23;
count=0
img_array = []
for filename in glob.glob('/Users/User/Desktop/eleventh_trial_2/*.tif'):
img = cv2.imread(filename)
height, width, layers = img.shape
size = (width,height)
img2 = io.imread(filename, as_gray=True)
fig, ax = plt.subplots()
ax.imshow(img)
#ax=pl.text(T1[i,1]+13,T1[i,0],str(int(T1[i,9])),color="red",fontsize=18)
T1=t.loc[t['frame']==count]
T1=np.array(T1.sort_values(by='particle'))
for i in Selector1:
pl.text(T1[i,1]+13,T1[i,0],str(int(T1[i,9])),color="red",fontsize=18)
circle2 = plt.Circle((T1[i,1], T1[i,0]), 5, color='r', fill=False)
ax.add_artist(circle2)
count=count+1
img_array.append(fig)
ani = animation.ArtistAnimation(fig, img_array, interval=50, blit=True,repeat_delay=1000)
When I run this I don't get an an error however I can't save the ani as tried in the past either using OpenCV videoWriter.
I found a work around although not the most efficient one. I saved the figures in a separate directory using os and plt.savefig() and then use ImageJ to automatically convert the sequentially numbered and saved figures into an animation. It ain't efficient but gets the job done. I am still open to more efficient answers. Thanks

How to select irregular shapes in a image

Using python code we are able to create image segments as shown in the screenshot. our requirement is how to select specific segment in the image and apply different color to it ?
The following is our python snippet
from skimage.segmentation import felzenszwalb, slic,quickshift
from skimage.segmentation import mark_boundaries
from skimage.util import img_as_float
import matplotlib.pyplot as plt
from skimage import measure
from skimage import restoration
from skimage import img_as_float
image = img_as_float(io.imread("leaf.jpg"))
segments = quickshift(image, ratio=1.0, kernel_size=20, max_dist=10,return_tree=False, sigma=0, convert2lab=True, random_seed=42)
fig = plt.figure("Superpixels -- %d segments" % (500))
ax = fig.add_subplot(1, 1, 1)
ax.imshow(mark_boundaries(image, segments))
plt.axis("off")
plt.show()
do this:
seg_num = 64 # desired segment to be colored
color = float64([1,0,0]) # red color
image[segments == 64] = color # assign color to the segment
You can use OpenCV python module - example:

Image is not displayed in python

I am writing the following code for display image in my window but image is not displayed. Only blank window appearing.
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from Tkinter import *
import matplotlib, sys
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
from matplotlib import pylab as plt
root=Tk()
fr=Frame(root)
fr.pack()
image = mpimg.imread("C:\Users\Public\Pictures\SamplePictures\Koala.jpg")
f = Figure(figsize=(5,5), dpi=100)
im=plt.imshow(image)
canvas = FigureCanvasTkAgg(f, fr)
canvas.show()
canvas.get_tk_widget().pack(side='top', fill='both', expand=1)
root.mainloop()
Above question have solution to display image in canvas. we need to replace
f= Figure(figsize=(5,5), dpi=100) into f=plt.figure(figsize=(5,5), dpi=100) this line

resize images in python

Can i resize images in python to given height and width,i use python 2.5, and i tried as this tutorial http://effbot.org/imagingbook/introduction.htm, and i installed PIL library for images,but when i try to write:
import Image
im = Image.open("test.jpg")
i got undefined variable from import:open
although import Imagedoesn't give errors?
Thanks in advance.
Your import appears to be the problem. Use this instead of "import Image":
from PIL import Image
Then go on like so:
image = Image.open('/example/path/to/image/file.jpg/')
image.thumbnail((80, 80), Image.ANTIALIAS)
image.save('/some/path/thumb.jpg', 'JPEG', quality=88)
To whom it may be of use: Just found that on the official Pillow website. You probably used Pillow and not PIL.
Warning
Pillow >= 1.0 no longer supports “import Image”. Please use “from PIL
import Image” instead.
This script resizes all images in a given folder:
import PIL
from PIL import Image
import os, sys
path = "path"
dirs = os.listdir( path )
def resize():
for item in dirs:
if os.path.isfile(path+item):
img = Image.open(path+item)
f, e = os.path.splitext(path+item)
img = img.resize((width,hight ), Image.ANTIALIAS)
img.save(f + '.jpg')
resize()
you can resize image using skimage
from skimage.transform import resize
import matplotlib.pyplot as plt
img=plt.imread('Sunflowers.jpg')
image_resized =resize(img, (244, 244))
plotting resized image
plt.subplot(1,2,1)
plt.imshow(img)
plt.title('original image')
plt.subplot(1,2,2)
plt.imshow(image_resized)
plt.title('image_resized')
for further code illustration : scikit-image
import os
from PIL import Image
imagePath = os.getcwd() + 'childFolder/myImage.png'
newPath = os.getcwd() + 'childFolder/newImage.png'
cropSize = 150, 150
img = Image.open(imagePath)
img.thumbnail(cropSize, Image.ANTIALIAS)
img.save(newPath)
if you have troubles with PIL the other alternative could be scipy.misc library. Assume that you want to resize to size 48x48 and your image located in same directory as script
from from scipy.misc import imread
from scipy.misc import imresize
and then:
img = imread('./image_that_i_want_to_resize.jpg')
img_resized = imresize(img, [48, 48])

Resources