Showing posts with label pillow. Show all posts
Showing posts with label pillow. Show all posts

9/19/2023

print image exif python code

 refer to code:


.

from PIL import Image, ExifTags
import os

def print_exif_data(directory_path):
"""
Print the EXIF data of every JPEG image in the given directory.
Args:
directory_path (str): Path to the directory containing JPEG images.
"""
# Loop through all files in the directory
for filename in os.listdir(directory_path):
if filename.lower().endswith('.jpg') or filename.lower().endswith('.jpeg'):
filepath = os.path.join(directory_path, filename)
# Open image file
image = Image.open(filepath)
# Extract EXIF data
exif_data = image._getexif()
if exif_data is not None:
# Print EXIF data
print(f"EXIF data for {filename}:")
for tag_id, value in exif_data.items():
tag_name = ExifTags.TAGS.get(tag_id, tag_id)
print(f"{tag_name} ({tag_id}): {value}")
print('-' * 50)
else:
print(f"No EXIF data found for {filename}")
print('-' * 50)

if __name__ == "__main__":
# Define the directory path
directory_path = "/your_path/images"
# Print EXIF data
print_exif_data(directory_path)

..


this is example result 

.




EXIF data for IMG_5602.JPG:
ResolutionUnit (296): 2
ExifOffset (34665): 224
Make (271): Apple
Model (272): iPhone 12 Pro
Software (305): 16.6.1
Orientation (274): 6
DateTime (306): 2023:09:18 16:32:55
YCbCrPositioning (531): 1
XResolution (282): 72.0
YResolution (283): 72.0
HostComputer (316): iPhone 12 Pro
ExifVersion (36864): b'0232'
ComponentsConfiguration (37121): b'\x01\x02\x03\x00'
ShutterSpeedValue (37377): 5.915630897377497
DateTimeOriginal (36867): 2023:09:18 16:32:55
DateTimeDigitized (36868): 2023:09:18 16:32:55
ApertureValue (37378): 1.3561438092556088
BrightnessValue (37379): 2.0295000055765606
ExposureBiasValue (37380): 0.0
MeteringMode (37383): 5
Flash (37385): 16
FocalLength (37386): 4.2
ColorSpace (40961): 65535
ExifImageWidth (40962): 4032
FocalLengthIn35mmFilm (41989): 26
SceneCaptureType (41990): 0
OffsetTime (36880): +03:00
OffsetTimeOriginal (36881): +03:00
OffsetTimeDigitized (36882): +03:00
SubsecTimeOriginal (37521): 447
SubsecTimeDigitized (37522): 447
ExifImageHeight (40963): 3024
SensingMethod (41495): 2
ExposureTime (33434): 0.016666666666666666
FNumber (33437): 1.6
SceneType (41729): b'\x01'
ExposureProgram (34850): 2
ISOSpeedRatings (34855): 160
ExposureMode (41986): 0
FlashPixVersion (40960): b'0100'
WhiteBalance (41987): 0
LensSpecification (42034): (4.2, 4.2, 1.6, 1.6)
LensMake (42035): Apple
LensModel (42036): iPhone 12 Pro back camera 4.2mm f/1.6
MakerNote (37500): b"Apple iOS\x00\x00\x01MM\x00,\x00\x01\x00\t\x00\x00\x00\x0....

..


this is code to update exif

.

from PIL import Image
from PIL.ExifTags import TAGS, TAGS_V2

def update_exif_dimensions(image_path):
# Open the image
img = Image.open(image_path)
# Get EXIF data
exif_data = img._getexif()
# Convert it to a dictionary for easier access
exif_dict = {TAGS.get(k, k): v for k, v in exif_data.items()}
# Update ExifImageWidth and ExifImageHeight with actual dimensions
exif_dict['ExifImageWidth'] = img.width
exif_dict['ExifImageHeight'] = img.height
# Update the EXIF data in the image
img._getexif().update(exif_dict)
# Save the image with updated EXIF data
img.save(image_path)

# Update for a specific image
image_path = "path/to/your/image.jpg" # Replace with the actual path to your image
update_exif_dimensions(image_path)


..


Thank you.

🙇🏻‍♂️

www.marearts.com

2/26/2023

Drawing rectangle and text on image using cv2, pillow (python code)

 Draw text & rectangle on image





Ver.1 pillow

.

from PIL import Image, ImageDraw, ImageFont
import json
# Display the image in Jupyter Notebook
from IPython.display import display


def draw_rect_text(base_dir, json_fn):
# Load JSON file
with open(base_dir+json_fn, 'r') as f:
data = json.load(f)

# Load image
img = Image.open(base_dir+data['image_file_name']+'.jpg')

# Create a draw object
draw = ImageDraw.Draw(img)

# Loop through OCR data and draw rectangles and text
for ocr in data['ocr']:
left = ocr['left']
top = ocr['top']
right = ocr['right']
bottom = ocr['bottom']
text = ocr['text']

# Draw rectangle
draw.rectangle((left, top, right, bottom), outline=(255, 0, 0), width=2)

# Draw text
font = ImageFont.truetype('arial.ttf', size=14)
text_size = draw.textsize(text, font=font)
text_x = left
text_y = top - text_size[1]
draw.text((text_x, text_y), text, font=font, fill=(255, 0, 0))

# Display image
# img.show() #now window
display(img) #display on notebook

..


Ver .2 cv2

.

import cv2
import json

def draw_rect_text(base_dir, json_fn):
# Load JSON file
with open(base_dir+json_fn, 'r') as f:
data = json.load(f)

print(base_dir+data['image_file_name']+'.jpg')
# Load image
img = cv2.imread(base_dir+data['image_file_name']+'.jpg')

# Loop through OCR data and draw rectangles and text
for ocr in data['ocr']:
left = ocr['left']
top = ocr['top']
right = ocr['right']
bottom = ocr['bottom']
text = ocr['text']
# Draw rectangle
cv2.rectangle(img, (left, top), (right, bottom), (0, 0, 255), 2)
# Draw text
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.5
thickness = 1
text_size = cv2.getTextSize(text, font, font_scale, thickness)[0]
text_x = left
text_y = top - text_size[1]
cv2.putText(img, text, (text_x, text_y), font, font_scale, (0, 0, 255), thickness)
# Display image
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

..


Thank you.

🙇🏻‍♂️

www.marearts.com

1/23/2023

PIL image to tensor

 refer to code

key is "transforms.PILToTensor"

..

import torch
from PIL import Image
import torchvision.transforms as transforms
pil_image = Image.open('input.jpg')
transform = transforms.Compose([
transforms.PILToTensor()
])
tensor_img = transform(pil_image)
print(tensor_img)

..


Thx. 🙇🏻‍♂️

12/08/2021

Rotation(orientation) correction when uploading photos from mobile (python, pillow)

 Try to use ImageOps function.

Solution is simple refer to below code:

.

#pip install Pillow
from PIL import Image, ImageOps
image = Image.open('img.jpg') #open image
#### orient fix
image = ImageOps.exif_transpose(image)
#### go futher!

.


Thank you.

🙇🏻‍♂️

www.marearts.com


8/08/2019

PIL to string, string to PIL (python)

It's simple example source code for that:

PIL to string(base64)
- PIL open image
- image to byte
- byte to string (base64)

string(base64) to PIL
- string to byte
- PIL load byte

--
import base64
import io
from PIL import Image

#open file using PIL
pil_img = Image.open('IMG_0510.jpg')
width, height = pil_img.size
print(width, height)


#get image data as byte
buffer = io.BytesIO()
pil_img.save(buffer, format=pil_img.format)
buffer_value = buffer.getvalue()

#byte to string
base64_str = base64.b64encode(buffer_value)

#read string to image buffer
buffer2 = base64.b64decode(base64_str)
pil_img2 = Image.open(io.BytesIO(buffer2))
width2, height2 = pil_img2.size
print(width2, height2)


#check first & second image
pil_img.show()
pil_img2.show()
--

here, another source code for :
OpenCV -> PIL -> resize -> OpenCV

http://study.marearts.com/2019/06/opencv-pil-resize-opencv.html

6/10/2019

OpenCV -> PIL -> resize -> OpenCV

Some simple code for this processing

1. Read image by OpenCV
2. Conver from OpenCV to PIL image
3. some processing using PIL, ex)resize
4. Conver from PIL to OpenCV

Check this code.


import cv2
from PIL import Image
import numpy

#target resize
r_x = 100
r_y = 100


#read image using opencv
cv_img_o = cv2.imread('A.png')

#conver mat to pil
cv_img = cv2.cvtColor(cv_img_o, cv2.COLOR_BGR2RGB)
im_pil = Image.fromarray(cv_img)

#resize pil
im_pil = im_pil.resize((r_x,r_y), Image.ANTIALIAS)

#convert pil to mat
cv_img_r = numpy.array(im_pil)

# Convert RGB to BGR
cv_img_r = cv2.cvtColor(cv_img_r, cv2.COLOR_RGB2BGR)
#cv_img_r = cv_img_r[:, :, ::-1].copy()

cv2.namedWindow('origin',0)
cv2.imshow('origin', cv_img_o)

cv2.namedWindow('resize',0)
cv2.imshow('resize', cv_img_r)

cv2.waitKey(0)

2/23/2019

64base image to pil image and upload s3 bucket on aws lambda

This article is about how to convert base64 string image to byte and invoke to PIL image.
Then we can handle image whatever we want to ex) image resize ..

base64 image come from img_base64 = event['base64Image']
and then convert to byte data imgdata = base64.b64decode(img_base64)

then it can save to image file and load to Image.open(filename)
or
invoke to pil image directly : img2 = Image.open(io.BytesIO(imgdata))

In the source code, there is also example how to upload image to s3 bucket.
refer to below code.
//
import sys
sys.path.append("/opt")

import json
import boto3
import os
import io
from PIL import Image
import base64



ACCESS_KEY = os.environ.get('ACCESS_KEY')
SECRET_KEY = os.environ.get('SECRET_KEY')

def uploadToS3(bucket, s3_path, local_path):
    s3_client = boto3.client(
        's3',
        aws_access_key_id=ACCESS_KEY,
        aws_secret_access_key=SECRET_KEY,
    )
    s3_client.upload_file(local_path, bucket, s3_path)
    
    
    
def lambda_handler(event, context):
    
    #base64 image string
    img_base64 = event['base64Image']
    #string to byte
    imgdata = base64.b64decode(img_base64)
    
    #save some image file
    with open("/tmp/imageToSave.png", "wb") as fh:
        fh.write(imgdata)
    
    #open("/tmp/imageToSave.png",'rb')
    uploadToS3("input-image1", "imageToSave.png", "/tmp/imageToSave.png")
    
    #load image file to pil
    img = Image.open("/tmp/imageToSave.png")
    width, height = img.size
    
    #load 
    img2 = Image.open(io.BytesIO(imgdata))
    width2, height2 = img2.size
    
    # TODO implement
    return {
        'statusCode': 200,
        'body': json.dumps('Hello leon it is from Lambda!'),
        'width file': width,
        'heihgt file' : height,
        'width pil': width2,
        'heihgt pil' : height2
    }

//

These method is referenced by:
https://stackoverflow.com/questions/16214190/how-to-convert-base64-string-to-image
https://stackoverflow.com/questions/11727598/pil-image-open-working-for-some-images-but-not-others
https://stackoverflow.com/questions/16214190/how-to-convert-base64-string-to-image
https://stackoverflow.com/questions/6444548/how-do-i-get-the-picture-size-with-pil

Thanks for effort.