Showing posts with label PIL. Show all posts
Showing posts with label PIL. 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

3/08/2023

download ttf font file


 download ttf font file: https://github.com/MareArts/font_ttf


Font Name
Arial
Arial Bold
Arial Bold Italic
Arial Italic
Courier New
Verdana
Verdana Bold
Verdana Bold Italic
Verdana Italic


www.marearts.com

Thank you.

πŸ™‡πŸ»‍♂️

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. πŸ™‡πŸ»‍♂️

3/01/2022

check image is single color or not, python , PIL image

 refer to example code

..

#get image data
image = Image.open(xxx)
image = image.convert('RGB')

#skip if image has one color
colors = image.getcolors(image.size[0]*image.size[1])
imgH = image.size[1]
imgW = image.size[0]
#print(f'img object w:{imgW}, h:{imgH}')
if len(colors) == 1:
continue

..


www.marearts.com

Thank you.

πŸ™‡πŸ»‍♂️

9/21/2021

python pil change dpi without save file

 


look at the code! ^^

..

#load image
tif_path = './input_img.tif'
#open image
pil_image = Image.open(tif_path)
#change dpi in memory
temp_mem_file = BytesIO()
page.save(temp_mem_file, format='png', dpi=(100,100))
#save it to pil
temp_mem_file.seek(0)
pil_image = Image.open(temp_mem_file)
#do it someting
#..
#save file
pil_image.save('./output.png')
#www.marearts.com
#study.marearts.com

..


Thank you.


10/02/2020

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)