Kernel restarts when compressing tif file using PIL in Anaconda - compression

I'm trying to compress a bunch of tiff files with the pillow package. However, when I'm executing the code in python3.7.13 in Spyder IDE within the Anaconda3 environment, the Kernel restarts in the line in which the tiff file should be compressed. I tried different compression methods (e.g. "group4", "zlib", "deflate", etc..).
I also tried other packages like libtiff and tifffile, but the same problem occurs here as well.
import os
import glob
from PIL import Image, TiffTags
from IPython.display import display
import numpy as np
images = [file for file in os.listdir("C:/Home/Slicer/tif") if file.endswith('tif')]
#search for alle the images in the path
for image in images:
img_name = str(image)
img = Image.open("C:/Home/Slicer/tif/"+img_name)
print(img_name + str(img))
display(img)
#save tiff file with new name
img.save("C:/Home/Slicer/tif/" + "compressed" + img_name, compression="tiff_lzw")
Console output

Related

Convert image to PDF with Django?

Receive multiple images as input from the user and convert them into PDF. I don't understand how to implement it with Django.
Use this command to install the packages
pip install img2pdf
Below is the implementation:
Image can be converted into pdf bytes using img2pdf.convert() functions provided by img2pdf module, then the pdf file opened in wb mode and is written with the bytes.
# Python3 program to convert image to pfd
# using img2pdf library
# importing necessary libraries
import img2pdf
from PIL import Image
import os
# storing image path
img_path = "C:/Users/Admin/Desktop/GfG_images/do_nawab.png"
# storing pdf path
pdf_path = "C:/Users/Admin/Desktop/GfG_images/file.pdf"
# opening image
image = Image.open(img_path)
# converting into chunks using img2pdf
pdf_bytes = img2pdf.convert(image.filename)
# opening or creating pdf file
file = open(pdf_path, "wb")
# writing pdf files with chunks
file.write(pdf_bytes)
# closing image file
image.close()
# closing pdf file
file.close()
# output
print("Successfully made pdf file")
Pillow supports PDF format. Documentation is available here.
from PIL import Image
img = Image.open('/path/to/image.jpg')
img = img.convert('RGB') //This removes alpha channel from .png images.
img.save('/path/to/image.pdf', format="PDF")

unable to clip raster(ETrF.etrf.tif) in python?

I have 50 rasters saved as LC81520412017282LGN00_ETrF.etrf.tif , and a polygon shapefile saved as a .shp.
as tried to clip this image using Clip(Data Management) in arcgis , it woks fine.but to process all image in bulk , I have written a script as below
import os
import arcpy
arcpy.env.workspace = "E:/Project"
for root, dirs, files in os.walk('E:/Project/a/r'):
for file in files:
if os.path.splitext(file)[1] == '.tif':
print (file)
arcpy.Clip_management(file,"#",
"E:/Project/be/test.gdb/%file%"
,"be/canal.shp","#","Clipping
Geometry", "NO_MAINTAIN_EXTENT")
the above script throws an error of "unsupported file or file doesn't exist".
the clip management is only to clip a shapefile to "Cut" a raster file using a shapefile you have to use
ExtractByMask (in_raster, in_mask_data)
here is an example
import arcpy
from arcpy import env
from arcpy.sa import *
env.workspace = "C:/sapyexamples/data"
outExtractByMask = ExtractByMask("elevation", "mask.shp")
outExtractByMask.save("C:/sapyexamples/output/maskextract")

Displaying PNG in matplotlib.pyplot framework in python 2.7

I am pulling PNG images from Jupyter Notebooks and manage to display with IPython.display.Image but not with matplotib.pyplot.plt. What am I missing? I use python 2.7.
I am using the following algorithm:
To open the notebook JSON content I do:
import nbformat
notebook_ = nbformat.read(file_notebook, 4)
After retrieving the relevant cell information I pull the png information from it using:
def cell_to_image(cell, out_value_item_number=1):
if "execution_count" in cell.keys(): # i.e version >=4
return cell["outputs"][out_value_item_number]['data']['image/png']
elif "prompt_number" in cell.keys(): # i.e version < 4
return cell["outputs"][out_value_item_number]['png']
return None
cell_image = cell_to_image(cell)
The first few characters of cell_image (which is unicode) looks like:
iVBORw0KGgoAAAANSUhEUgAAA64AAAFMCAYAAADLFeHSAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\n
AAALEgAACxIB0t1+/AAAIABJREFUeJzs3Xd8jef/x/HXyTjZiYQkCGrU3ruR0tr9oq2qGtGo0dbe
\nm5pVlJpFUSMoVb6UoEZ/lCpatWuPUiNEEiMDmef3R75OexonJKUO3s/HI4/mXPd1X/d1f+LRR965
\n7/u6DSaTyYSIiIiIiIiIjbJ70hMQERERERERyYiCq4iIiIiIiNg0BVcRERERERGxaQquIiIiIiIi
\nYtMUXEVERERERMSmKbiKiIiIiIiITVNwFRGRxyIkJIRixYqxfv36+24/e/YsxYoVo3jx4v/yzGxb
\naGgoderUIS4uDoBdu3bRsmVLKlasyCuvvMKgQYOIjo622CcsLIyGDRtSunRp6tSpw8KFC62OW7p0
\naRo2bJju53Lnzh1GjRrFyy+/TNmyZWnRogW//fbbQ835q6++olGjRpQvX5769eszc+ZMkpOTzdtT
\nU1OZNGkSNWrUoHTp0jRp0oTdu3enGyc2NpZOn
I can easily plot in my Jupityer notebook using
from IPython.display import Image
Image(cell_image)
And now to my question:
How can I manipulate cell_image to be plt.subplot friendly?
(Assuming import matplotlib.pyplot as plt).
I realise that plt.imshow wouldn't work because this would require an array, which is not my case (which is a string, as far as I understand).
If you have your image string representation in a variable string_rep, the following code should work.
from io import BytesIO
import matplotlib.image as mpimage
import matplotlib.pyplot as plt
with BytesIO(string_rep.decode('base64')) as byte_rep:
image = mpimage.imread(byte_rep)
plt.imshow(image)

Convert pdf to jpg using python 2.7- an error

I try to find a simple python code that convert hundred of pdf files to jpg files to the same folder where the pdf files located. I use this code from Python Wand converts from PDF to JPG background is incorrect
from wand.image import Image
from wand.color import Color
import os, os.path, sys
def pdf2jpg(source_file, target_file, dest_width, dest_height):
RESOLUTION = 300
ret = True
try:
with Image(filename=source_file, resolution=(RESOLUTION,RESOLUTION)) as img:
img.background_color = Color('white')
img_width = img.width
ratio = dest_width / img_width
img.resize(dest_width, int(ratio * img.height))
img.format = 'jpeg'
img.save(filename = target_file)
except Exception as e:
ret = False
return ret
if __name__ == "__main__":
source_file = r"C:\Users\yaron.KAYAMOT\Desktop\aaa.pdf"
target_file = r"C:\Users\yaron.KAYAMOT\Desktop\aaa.jpg"
ret = pdf2jpg(source_file, target_file, 1895, 1080)
but i get an error:
ImportError: MagickWand shared library not found.
You probably had not installed ImageMagick library.
Try to install:
http://docs.wand-py.org/en/latest/guide/install.html#install-imagemagick-on-windows
>>>
but i do have module MagickWand in the hard disk as shown in the cmd :
UPDATE:
when i try to pip install in the cmd "wand" module i get:
so,i do have this module. When i try to pip install imagemagick \ ImageMagick i get:
You're importing from wand module.
You probably haven't installed bindings for Python.
pip install Wand
See the details here: http://docs.wand-py.org/en/0.4.2/
Also try to do the following:
pip search pythonmagick
or something like that. Try to install all required packages.
This may help you.

Python - fetching image from urllib and then reading EXIF data from PIL Image not working

I use the following code to fetch an image from a url in python :
import urllib
from PIL import Image
urllib.urlretrieve("http://www.gunnerkrigg.com//comics/00000001.jpg", "00000001.jpg")
filename = '00000001.jpg'
img = Image.open(filename)
exif = img._getexif()
However, this way the exif data is always "None". But when I download the image by hand and then read the EXIF data in python, the image data is not None.
I have also tried the following approach (from Downloading a picture via urllib and python):
import urllib
f = open('00000001.jpg','wb')
f.write(urllib.urlopen('http://www.gunnerkrigg.com//comics/00000001.jpg').read())
f.close()
filename = '00000001.jpg'
img = Image.open(filename)
exif = img._getexif()
But this gives me 'None' for 'exif' again. Could someone please point out what I may do to solve this problem?
Thank you!
The .jpg you are using contains no exif information. If you try the same python with an exif example from http://www.exif.org/samples/ , I think you will find it works.