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])
Related
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
I am was trying out one of the sample Python scripts available from the web site of Scikit Image. This script demonstrates Otsu segmentation at a local level. The script works with pictures loaded using
data.page()
but not using
io.imread
. Any suggestions?
https://scikit-image.org/docs/dev/auto_examples/applications/plot_thresholding.html#sphx-glr-auto-examples-applications-plot-thresholding-py
Picture file
Actual output - the Local thresholding window is empty
As you can see, Global thresholding has worked.But Local Thresholding has failed to produce any results.
Strangely, if I use data.page() then everything works fine.
Script
from skimage import io
from skimage.color import rgb2gray
import matplotlib.pyplot as plt
from skimage.filters import threshold_otsu,threshold_local
import matplotlib
from skimage import data
from skimage.util import img_as_ubyte
filename="C:\\Lenna.png"
mypic= img_as_ubyte (io.imread(filename))
#image = data.page() #This works - why not io.imread ?
imagefromfile=io.imread(filename)
image = rgb2gray(imagefromfile)
global_thresh = threshold_otsu(image)
binary_global = image > global_thresh
block_size = 35
local_thresh = threshold_local(image, block_size, offset=10)
binary_local = image > local_thresh
fig, axes = plt.subplots(nrows=3, figsize=(7, 8))
ax = axes.ravel()
plt.gray()
ax[0].imshow(image)
ax[0].set_title('Original')
ax[1].imshow(binary_global)
ax[1].set_title('Global thresholding')
ax[2].imshow(binary_local)
ax[2].set_title('Local thresholding')
for a in ax:
a.axis('off')
plt.show()
If you load the lenna.png and print its shape you will see it is a 4-channel RGBA image rather than a 3-channel RGB image.
print mypic.shape
(512, 512, 4)
I am not sure which parts of your code apply to which image, so I am not sure where to go next, but I guess you want to just get the RGB part and discard the alpha:
RGB = mypic[...,:3]
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)
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:
I am trying to display a wxpython screen shot in pyplot but I dont want to save the image.
this is what I have
import wx
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
thisApp = wx.App( redirect=False )
def saveSnapshot(dcSource): #takes arg dcSource
# based largely on code posted to wxpython-users by Andrea Gavana 2006-11-08
size = dcSource.Size
bmp = wx.EmptyBitmap(size.width, size.height)
memDC = wx.MemoryDC()
memDC.SelectObject(bmp)
memDC.Blit( 0, 0, size.width, size.height, dcSource, 0, 0)
memDC.SelectObject(wx.NullBitmap)
img = bmp.ConvertToImage()
img.SaveFile('saved.png', wx.BITMAP_TYPE_PNG)
img = mpimg.imread('saved.png')
plt.imshow(img)
plt.show()
saveSnapshot(wx.ScreenDC())
this is something like what I want, basically not to save the file just display it.
img = bmp.ConvertToImage()
plt.imshow(img)
plt.show()
You can use a BytesIO object. A possible solution would be:
import wx
from matplotlib import pyplot as plt
from io import BytesIO
thisApp = wx.App(redirect=False)
def saveSnapshot(dcSource):
size = dcSource.Size
bmp = wx.EmptyBitmap(size.width, size.height)
memDC = wx.MemoryDC()
memDC.SelectObject(bmp)
memDC.Blit( 0, 0, size.width, size.height, dcSource, 0, 0)
memDC.SelectObject(wx.NullBitmap)
img = bmp.ConvertToImage()
bio = BytesIO()
bs = wx.OutputStream(bio)
img.SaveStream(bs, wx.BITMAP_TYPE_PNG)
bio.seek(0) #rewind stream
plt.imshow(plt.imread(bio))
plt.show()
saveSnapshot(wx.ScreenDC())
I found some ideas for this approach here.
Update:
A slightly different approach using pyscreenshot could look like:
import matplotlib.pyplot as plt
import pyscreenshot as ImageGrab
def saveSnapshot():
im = ImageGrab.grab()
plt.imshow(im)
plt.show()