Display a .png image from python on mint-15 linux - python

I am trying to display a .png file I constructed using the following.
import pydot, StringIO
dot_data = StringIO.StringIO()
tree.export_graphviz( clf, out_file = dot_data,
feature_names =['age', 'sex', 'first_class', 'second_class', 'third_class'])
graph = pydot.graph_from_dot_data( dot_data.getvalue())
graph.write_png('titanic.png')
from IPython.core.display import Image
Image( filename ='titanic.png')
I tried the following but neither errors nor .png are displayed:
from PIL import Image
image = Image.open("titanic.png")
image.show()

if you just want to display it, you may use matplotlib:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img = mpimg.imread('file-name.png')
plt.imshow(img)
plt.show()

Related

Converting Tiff file to JPG or Png python

Hi i am trying to convert the Tiff file into png or jpg file but the ouput that i am getting is noisy and not what i expected. Below is the code that i have tried :
from PIL import Image
im = Image.open('/content/img.tif')
import numpy as np
imarray = np.array(im)
print(imarray)
from matplotlib import pyplot as plt
plt.imshow(imarray, interpolation='nearest')
plt.show() # To see how the tiff file looks like
import cv2
from PIL import Image, ImageOps
img = (np.maximum(imarray, 0) / imarray.max()) * 255.0
print(img)
img = 255 - img #Inverting the pixel
print("********************************************************************")
print(img)
img = Image.fromarray(np.uint8(img))
img.save(f'/content/img.png')
please find the sample tiff file here
https://drive.google.com/file/d/1Gfyo4dCo_4pfYvUn6_a6lD0SfxZOzUwK/view?usp=sharing
Output png/jpg image i was getting is this
Can anyone please help me in converting the tiff into jpg or png
Thanks
The code below worked for me to read .tiff image and save layers as .jpeg:
from PIL import Image, ImageSequence
#open tiff image
im = Image.open("YOUR IMAGE PATH")
#navigate to the folder were the layers are going to be saved
%cd YOUR DIRECTORY
#loop over layers and export jpeg instances
for i, page in enumerate(ImageSequence.Iterator(im)):
page.mode = 'I'
page.point(lambda i:i*(1./256)).convert('L').save(str(i)+'.jpeg')

How do I edit multiple files in PIL

I was trying to edit alot of images at the same time using pil and python it shows me this error:
my code so far is below
import glob
import PIL
from PIL import Image
image = glob.glob('./*.png')
img = Image.open(image)
img.putalpha(127)
img.save("")
you may try this:
import glob
import PIL
from PIL import Image
for i in glob.glob('./*.png'):
img = Image.open(i)
img.putalpha(127)
img.save("")

How do you load an image on VSC for Python

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
image = mpimg.imread('25.png')
plt.imshow(image)
I've used this code here to try and produce the image but it keeps saying that the module does not exist.
First, you should import 'matplotlib.pyplot'
Second, make sure the photo is in the same directory as your code is.
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
image = mpimg.imread('25.png')
imgplot = plt.imshow(image)

matplotlib is not showing output in simple tutorial program

import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib
img = cv2.imread('flood.jpg',0)
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([])
plt.show()
Above is my code and when I run this program Ii get
"/home/badal/Python-3.7.1/image_process/im2.py:9: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
plt.show()
After using tkagg I get
"Traceback (most recent call last):
File "/home/badal/Python-3.7.1/image_process/im2.py", line 5, in
import tkinter as tk
File "/usr/local/lib/python3.7/tkinter/init.py", line 36, in
import _tkinter # If this fails your Python may not be configured for Tk ModuleNotFoundError: No module named '_tkinter'"
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib
import tkinter as tk
matplotlib.use('tkagg')
img = cv2.imread('flood.jpg',0)
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([])
plt.show()
I have already installed tkinter, so I don't know what to do.
I think that the problem is on cv2 module that I don't know what is.
img = cv2.imread('flood.jpg',0)
However I made some changes.
First of all I don't import cv2 module.
Second I import Image from PIL.
And to open the pic I made
img = Image.open('flood.jpg')
So your code becomes:
import numpy as np
#import cv2
import matplotlib.pyplot as plt
import matplotlib
from PIL import Image
img = Image.open('flood.jpg')
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([])
plt.show()

Error with image Python IO in-memory stream save and use

Currently I am trying to plot my DataFrame data and add to my pptx slide. I used matplotlib + pptx-python to do the work. In the process, I tried to save the plot image to io in-memory stream and use it for pptx slide. The steps are:
import io
from PIL import Image
from pptx import Presentation
from pptx.util import Inches
#1. Run Python-pptx and open presentation
prs = Presentation('Template.pptx')
title_slide_layout = prs.slide_layouts[6]
slide = prs.slides.add_slide(title_slide_layout)
title = slide.shapes.title
title.text = 'FileName'
left = top = Inches(1)
#2. plot the data in matplotlib
fig, ax = plt.subplots()
df.groupby('Name').plot(x='Time',y='Score', ax=ax)
#3. save the plot to io in-memory stream
buf = io.BytesIO()
fig.savefig(buf, format='png')
buf.seek(0)
im = Image.open(buf)
#4. add image to slide
pic = slide.shapes.add_picture(im, left, top)
But I got an error like this:
AttributeError: 'PngImageFile' object has no attribute 'read'
Do you know how to solve this problem? BTW I am using Python 3.6. I tried to update PIL package and use 'png' and 'jpg' formats for my image. All efforts didn't work.
Don't use PIL to open the .png file before giving it to .add_picture():
buf = io.BytesIO()
fig.savefig(buf, format='png')
buf.seek(0)
# ---skip the Image.open() step and feed buf directly to .add_picture()
pic = slide.shapes.add_picture(buf, left, top)
The .add_picture() method is looking for a file-like object containing an image, which is buf in this case. When you called Image.open() with buf you get a PIL image object of some sort, which is not what you need.

Categories