Image is not displayed in python - image

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

Related

Need help to create Confusion Matrix and Prediction Code

model_SVC = SVC(C=1000,gamma=0.1, kernel='rbf')
model_SVC.fit(X_train,Y_train) #CASIA2
predictions=model_SVC.predict(X_test)
print(accuracy_score(Y_test,predictions))
print(confusion_matrix(Y_test,predictions))
print(classification_report(Y_test,predictions))
I need help in creating a confusion matrix using seaborn and a code to predict the image.
Can someone help me with this?
I have used your code along with some random code to generate data and ConfusionMatrixDisplay to generate the confusion matrix. You can change the parameters as required to suit your needs.
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from sklearn.datasets import make_classification
from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
X, y = make_classification(random_state=0)
X_train, X_test, Y_train, Y_test = train_test_split(X, y, random_state=0)
model_SVC = SVC(C=1000,gamma=0.1, kernel='rbf')
model_SVC.fit(X_train,Y_train) #CASIA2
predictions=model_SVC.predict(X_test)
#print(accuracy_score(Y_test,predictions))
cm = confusion_matrix(Y_test,predictions)
#print(classification_report(Y_test,predictions))
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=model_SVC.classes_)
font={'size':'14'}
plt.rc('font',**font)
plt.rcParams['figure.figsize']=[6,6]
disp.plot(cmap='Blues',values_format='0.2f')
#plt.colorbar(im,fraction=0.046, pad=0.04)
plt.show()
Plot

when resizing a image set only resizing one 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)

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:

how to directly convert wxpython image to pyplot image without saving

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()

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