Converting Tiff file to JPG or Png python - 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')

Related

How to Image.open a RAW (CR2) file in python?

I have the following code for a .tif file:
img = Image.open("randompic.tif")
image = Jpeg()
image.encodeRGB("randompic.tif")
print(np.array_equal(image.total_bit_objects, np.asarray(Image.open('randompic.tif').convert('L'))))
I try to adapt it for a .CR2 file :
img = np.fromfile('IMG_4387.CR2', "uint16")
image = Jpeg()
image.encodeRGB("IMG_4387.CR2")
print(np.array_equal(image.total_bit_objects, np.asarray(Image.open('IMG_4387.CR2').convert('L'))))
However, Image.open('IMG_4387.CR2') does not work.
Do you have any idea to fix me ?
Why not try the following code. It uses simple PIL
I tried rawpy and rawkit and they had complications with Libraw.
Rawpy worked but performed a postprocessing I could not seem to understand
from PIL import Image
im = Image.open("File.CR2")
rgb_im = im.convert('RGB')
rgb_im.save('File.JPG')

Where are images saved when creating images with Pillow in Python

In these lines of code, I create a small red image and save it as "new_image.png". But I can't find the saved image, where is it saved? And can I change the place where I want to save my image?
from PIL import Image
img = Image.new('RGB', (60, 30), color = 'red')
img.save("new_image.PNG")
I tested your code:
from PIL import Image
img = Image.new('RGB', (60, 30), color = 'red')
img.save("new_image.PNG")
It works well for me:
The reason may because your current work path is not as you thought.
See my answer here:
https://stackoverflow.com/a/66449241/12838403
If you don't specify a path, the image is saved in the same path as the python file generating the image
from PIL import Image
img = Image.new('RGB', (60, 30), color = 'red')
img.save("new_image.PNG")
To save image in a directory you specify, you can use
from PIL import Image
import os
image_path = "path/to/image"
image = image.save(f"{image_path}/image.png")
Note: If this directory does not exist, you would have to create it before saving your image in it.
from PIL import Image
import os
image_path = "path/to/image"
os.mkdir(image_path)
image = image.save(f"{image_path}/image.png")

Converting Image to Bytearray with Python

I want to convert Image file to Bytearray. I extracted image from pdf file with minecart lib, but I cant find a way to convert it to bytearray. This is my code:
import minecart
from PIL import Image
import io
pdffile = open('sample6.pdf', 'rb')
doc = minecart.Document(pdffile)
for page in doc.iter_pages():
print(page)
img = page.images[0].as_pil()
print(img) # <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=1641x2320 at 0x7FBDF02E6A00>
print(type(img)) # <class 'PIL.JpegImagePlugin.JpegImageFile'>
I have tried to use bytearray(img) but It does not work.
Do you have solution for this (solution that does not consume to much time)?
Create io.BytesIO buffer and write to it using PIL.Image.save. Set appropriate quality and other parameters as per requirement.
import io
from PIL import Image
def convert_pil_image_to_byte_array(img):
img_byte_array = io.BytesIO()
img.save(img_byte_array, format='JPEG', subsampling=0, quality=100)
img_byte_array = img_byte_array.getvalue()
return img_byte_array
References:
Why is the quality of JPEG images produced by PIL so poor?

How to resize base64 encoded image in python

I want resize base64 encoded image in python.I searched I could not find. I used Pillow package to do it. However, Pillow has no such kind of feature .
This code does the job (Python 3):
import io
import base64
from PIL import Image
base64_str = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
buffer = io.BytesIO()
imgdata = base64.b64decode(base64_str)
img = Image.open(io.BytesIO(imgdata))
new_img = img.resize((2, 2)) # x, y
new_img.save(buffer, format="PNG")
img_b64 = base64.b64encode(buffer.getvalue())
print(str(img_b64)[2:-1])
EDIT: Reducing the size of a base64 image does not imply reducing the file size.

image to text conversion using Tesseract

I am trying to load all images in a folder and extract text from images. I keep getting error message for the second for loop. For example,
AttributeError: 'numpy.ndarray' object has no attribute 'read'
It seems I cannot access list Img. Any idea?
# import OpenCV, Numpy, Python image library, Tesseract OCR
import os
import cv2
import numpy
from PIL import Image
import pytesseract
import glob
#set tesseract path
pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files (x86)/Tesseract-OCR/tesseract.exe'
#read all image with .jpg format in a specifying folder
img = []
for i in glob.glob("C:\\Users\\daizhang\\Desktop\\Deloitte Development\\Python\\Reports\\Image\\*.jpg"):
n= cv2.imread(i,0) #convert image to grayscale
print(i)
img.append(n)
for j in img:
im = Image.open(j)
text = pytesseract.image_to_string (j, lang='eng')
with open("C:\\Users\\daizhang\\Desktop\\Deloitte Development\\Python\Reports\\Image\\test.txt", "w") as f:
f.write(text.encode('utf8'))
I have Mac OSX but you can adjust this code to file Window's path directory.
import os
from os import path
from glob import glob
from pytesseract import image_to_string
from PIL import Image, ImageEnhance, ImageFilter
def enhance_img(filename):
# Enhance image and save as under new name
im = im.filter(ImageFilter.MedianFilter())
enhancer = ImageEnhance.Contrast(im)
im = enhancer.enhance(2)
im = im.convert('1')
im.save('newfilename')
def convert_img(filename):
image = Image.open(filename)
# Convert image to text
file = open ('parsing.txt', 'a')
file.write(image_to_string(image))
file.close
def find_ext(dir, ext):
return glob(path.join(dir, "*.{}".format(ext)))
# use the following for change directory
# os.chdir(path)
filename = find_ext("","png")
for file in filename:
# convert image to text
convert_img(file)
If you want to enhance the image then include the following block and adjust the code above to loop through the new filenames.
def enhance_img(filename):
# Enhance image and save as under new name
im = im.filter(ImageFilter.MedianFilter())
enhancer = ImageEnhance.Contrast(im)
im = enhancer.enhance(2)
im = im.convert('1')
im.save('newfilename')
For file in filename:
# to enhance image if needed
newfilename = filename[-3] + '_1.png'
enhance_img(file)

Categories