how to directly convert wxpython image to pyplot image without saving - image

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

Related

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:

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

pyplot.imsave() saves image correctly but cv2.imwrite() saved the same image as black

from scipy.misc import imread
from matplotlib import pyplot
import cv2
from cv2 import cv
from SRM import SRM ## Module for Statistical Regional Segmentation
im = imread("lena.png")
im2 = cv2.imread("lena.png")
print type(im), type(im2), im.shape, im2.shape
## Prints <type 'numpy.ndarray'> <type 'numpy.ndarray'> (120, 120, 3) (120, 120, 3)
srm = SRM(im, 256)
segmented = srm.run()
srm2 = SRM(im2, 256)
segmented2 = srm2.run()
pic = segmented/256
pic2 = segmented2/256
pyplot.imshow(pic)
pyplot.imsave("onePic.jpg", pic)
pic = pic.astype('uint8')
cv2.imwrite("onePic2.jpg", pic2)
pyplot.show()
onePic.jpg gives the correct segmented image but onePic2.jpg gives a complete black image.
Converting the datatype to uint8 using pic = pic.astype('uint8') did not help. I still gives a black image!
onePic.jpg using pyplot.imsave():
onePic2.jpg using cv2.imwrite():
Please help!
Before converting pic to uint8, you need to multiply it by 255 to get the correct range.
Although I agree with #sansuiso, in my case I found a possible edge case where my images were being shifted either one bit up in the scale or one bit down.
Since we're dealing with unsigned ints, a single shift means a possible underflow/overflow, and this can corrupt the whole image.
I found cv2's convertScaleAbs with an alpha value of 255.0 to yield better results.
def write_image(path, img):
# img = img*(2**16-1)
# img = img.astype(np.uint16)
# img = img.astype(np.uint8)
img = cv.convertScaleAbs(img, alpha=(255.0))
cv.imwrite(path, img)
This answer goes into more detail.
I encountered a similar situation with face detection, I wonder if there is a better way to execute this, here is my solution here as a reference.
from deepface import DeepFace
import cv2
import matplotlib.pyplot as plt
# import image and output
img_path = "image.jpg"
detected_face = DeepFace.detectFace(img_path, target_size = (128, 128))
plt.imshow(detected_face)
# image color scaling and saving
detected_face = cv2.cvtColor( detected_face,cv2.COLOR_BGR2RGB)
detected_face = cv2.convertScaleAbs(detected_face, alpha=(255.0))
cv2.imwrite("image_thumbnail.jpg", detected_face)

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