Skip to content

Instantly share code, notes, and snippets.

@addohm
Last active February 27, 2023 16:12
Show Gist options
  • Save addohm/8a87d284afa927f38dd1fbdbd1fafa9f to your computer and use it in GitHub Desktop.
Save addohm/8a87d284afa927f38dd1fbdbd1fafa9f to your computer and use it in GitHub Desktop.
Strip image background with rembg and copy metadata to new image with pyexiftool
# import required module
import os
import cv2
import exiftool
import rembg
# assign path variables
VERBOSE = False
BASE_DIRECTORY = os.getcwd()
DESKTOP_DIRECTORY = os.path.expanduser("~\\Desktop")
INPUT_DIRECTORY = os.path.join(BASE_DIRECTORY, 'input')
OUTPUT_DIRECTORY = os.path.join(BASE_DIRECTORY, 'output')
EXIFTOOL_PATH = os.path.join(BASE_DIRECTORY, 'exiftool(-k).exe')
def main():
if not os.path.exists(INPUT_DIRECTORY):
os.makedirs(INPUT_DIRECTORY)
print(f"Please add files to the input directory located at {INPUT_DIRECTORY}")
quit()
if not os.path.exists(OUTPUT_DIRECTORY):
os.makedirs(OUTPUT_DIRECTORY)
if not os.path.exists(EXIFTOOL_PATH):
quit()
# Count the files in the image directory
count = 0
for f in os.listdir(INPUT_DIRECTORY):
if os.path.isfile(os.path.join(INPUT_DIRECTORY, f)):
count += 1
print(f"Detected {count} files in the input directory folder.")
if count > 0:
with exiftool.ExifToolHelper(executable=EXIFTOOL_PATH) as et:
'''
iterate over all the files in the input path and
remove the background from the image. Save the image
as a JPEG and copy the metadata over to the new file.
'''
for filename in os.listdir(INPUT_DIRECTORY):
# define the full input and output paths
input_path = os.path.join(INPUT_DIRECTORY, filename)
output_path = os.path.join(OUTPUT_DIRECTORY, filename)
# read the original image
imin = cv2.imread(input_path)
# remove the background and save the image as a JPEG
imout = rembg.remove(imin)
cv2.imwrite(os.path.join(OUTPUT_DIRECTORY, filename), imout, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
# define the executable parameters and execute exiftool
exline = f"-TagsFromFile {input_path} -all:all {output_path} -overwrite_original"
if VERBOSE: print(f"Executing: {EXIFTOOL_PATH} {exline}")
et.execute('-TagsFromFile', input_path, '-all:all', output_path, '-overwrite_original')
# Decrement the count and print progress
count -= 1
print(f"{count} files remaining.")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment