Skip to content

Instantly share code, notes, and snippets.

@lucascompython
Created March 21, 2022 20:53
Show Gist options
  • Save lucascompython/626ced19f9c5e9040d30ffbc3e87bf95 to your computer and use it in GitHub Desktop.
Save lucascompython/626ced19f9c5e9040d30ffbc3e87bf95 to your computer and use it in GitHub Desktop.
This is a faster resizer that also applies an watermark image using opencv
import cv2, os
watermark = cv2.imread(os.path.join("watermark.jpg"))
h_wtmk, w_wtmk = watermark.shape[:2]
def resize(inpath: str, outpath: str, size: tuple = (768, 512), inter: int = cv2.INTER_AREA) -> None:
for infile in os.listdir(inpath):
try:
path = os.path.join(inpath, infile)
#checking for folders
if os.path.isdir(path):
continue
dim = None
img = cv2.imread(path)
img = img.copy()
h_img, w_img = img.shape[:2]
#adding watermark
#calculating coordiantes of center
center_y = h_img // 2
center_x = w_img // 2
#calculating from top, bottom, right and left
top_y = center_y - h_wtmk // 2
left_x = center_x - w_wtmk // 2
bottom_y = top_y + h_wtmk
right_x = left_x + w_wtmk
destination = img[top_y: bottom_y, left_x: right_x]
try:
result = cv2.addWeighted(destination, 1, watermark, 0.5, 0)
img[top_y: bottom_y, left_x: right_x] = result
except cv2.error:
print(f"Could not watermark: {infile}... Probably because the image is smaller than the watermark.")
return
if all(sizes == None for sizes in size):
return
if size[0] == None:
r = size[1] / w_img
dim = (int(w_img * r), size[1])
else:
r = size[0] / w_img
dim = (size[0], int(h_img * r))
resized = cv2.resize(img, dim, interpolation = inter)
#saving
cv2.imwrite(os.path.join(outpath, infile), resized)
print("Resized and Watermarked:", infile)
except IOError:
print("Cannot neither resized nor watermark:", infile)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment