Anbarasan Thangapalam
Anbarasan Thangapalam

Reputation: 1018

converting tiff to jpeg in python

Can anyone help me to read .tiff image and convert into jpeg format?

from PIL import Image
im = Image.open('test.tiff')
im.save('test.jpeg')

The above code was not working.

Upvotes: 34

Views: 104211

Answers (5)

shoytov
shoytov

Reputation: 605

I liked the solution suggested in this answer: https://stackoverflow.com/a/28872806/12808155 But checking for tiff in my opinion is not entirely correct, since there may be situations when the extension .tif does not define the file format: for example, when indexing, macOS creates hidden files ( ._DSC_123.tif).

For a more universal solution, I suggest using the python-magic library (https://pypi.org/project/python-magic) The code for checking for tiff format may look like this:

import magic

def check_is_tif(filepath: str) -> bool:
allowed_types = [
    'image/tiff',
    'image/tif'
]

if magic.from_file(filepath, mime=True) not in allowed_types:
    return False
return True

Complete code may looks like this:

import argparse
import os

import magic
from PIL import Image
from tqdm import tqdm


def check_is_tif(filepath: str) -> bool:
    allowed_types = [
        'image/tiff',
        'image/tif'
    ]

    if magic.from_file(filepath, mime=True) not in allowed_types:
        return False
    return True


def count_total(path: str) -> int:
    print('Please wait till total files are counted...')

    result = 0

    for root, _, files in os.walk(path):
        for name in files:
            if check_is_tif(os.path.join(root, name)) is True:
                result += 1

    return result


def convert(path) -> None:
    progress = tqdm(total=count_total(path))

    for root, _, files in os.walk(path):
        for name in files:
            if check_is_tif(os.path.join(root, name)) is True:
                file_path = os.path.join(root, name)
                outfile = os.path.splitext(file_path)[0] + ".jpg"
                
                try:
                    im = Image.open(file_path)
                    
                    im.thumbnail(im.size)
                    im.save(outfile, "JPEG", quality=80)
                    os.unlink(file_path)
                except Exception as e:
                    print(e)

                progress.update()


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Recursive TIFF to JPEG converter')
    parser.add_argument('path', type=str, help='Path do directory with TIFF files')
    args = parser.parse_args()
    
    convert(args.path)

Upvotes: 0

OMKAR GURAV
OMKAR GURAV

Reputation: 91

This can be solved with the help of OpenCV. It worked for me.
OpenCV version == 4.3.0

import cv2, os
base_path = "data/images/"
new_path = "data/ims/"
for infile in os.listdir(base_path):
    print ("file : " + infile)
    read = cv2.imread(base_path + infile)
    outfile = infile.split('.')[0] + '.jpg'
    cv2.imwrite(new_path+outfile,read,[int(cv2.IMWRITE_JPEG_QUALITY), 200])

Upvotes: 9

Boris
Boris

Reputation: 11

I believe all the answers are not complete

TIFF image format is a container for various formats. It can contain BMP, TIFF noncompressed, LZW compressions, Zip compressions and some others, among them JPG etc. image.read (from PIL) opens these files but cant't do anything with them. At least you can find out that it is a TIFF file (inside, not only by its name). Then one can use pytiff.Tiff (from pytiff package). For some reasons, when tiff has JPG compression (probably, some others too) it cannot encode the correct information.

Something is rotten in the state of Denmark (C)

P.S. One can convert file with help of Paint (in old windows Paint Brush (Something is rotten in this state too) or Photoshop - any version. Then it can be opened from PythonI'm looking for simple exe which can do it, the call it from python. Probably Bulk Image Converter will do

Upvotes: 1

user2019716
user2019716

Reputation: 643

import os, sys
from PIL import Image

I tried to save directly to jpeg but the error indicated that the mode was P and uncompatible with JPEG format so you have to convert it to RGB mode as follow.

for infile in os.listdir("./"):
    print "file : " + infile
    if infile[-3:] == "tif" or infile[-3:] == "bmp" :
       # print "is tif or bmp"
       outfile = infile[:-3] + "jpeg"
       im = Image.open(infile)
       print "new filename : " + outfile
       out = im.convert("RGB")
       out.save(outfile, "JPEG", quality=90)

Upvotes: 17

Anbarasan Thangapalam
Anbarasan Thangapalam

Reputation: 1018

I have successfully solved the issue. I posted the code to read the tiff files in a folder and convert into jpeg automatically.

import os
from PIL import Image

yourpath = os.getcwd()
for root, dirs, files in os.walk(yourpath, topdown=False):
    for name in files:
        print(os.path.join(root, name))
        if os.path.splitext(os.path.join(root, name))[1].lower() == ".tiff":
            if os.path.isfile(os.path.splitext(os.path.join(root, name))[0] + ".jpg"):
                print "A jpeg file already exists for %s" % name
            # If a jpeg is *NOT* present, create one from the tiff.
            else:
                outfile = os.path.splitext(os.path.join(root, name))[0] + ".jpg"
                try:
                    im = Image.open(os.path.join(root, name))
                    print "Generating jpeg for %s" % name
                    im.thumbnail(im.size)
                    im.save(outfile, "JPEG", quality=100)
                except Exception, e:
                    print e

Upvotes: 34

Related Questions