Python + cv2 exercises to resize jpg and save in bmp
Python + cv2 exercises to resize jpg and save in bmp, tested on Raspberry Pi 5/64 bit Raspberry Pi OS (bookworm).
py_cv_resize.py, resize jpg and save in bmp, the file name is hard-coded in the program. You can also save the image in other file name/format in cv.imwrite() interface.
# Python exercise to resize jpg and save in bmp
# tested on Raspberry Pi 5/64 bit Raspberry Pi OS (bookworm)
import cv2 as cv
target_width = 240
target_height = 240
path = "./images/"
file = "05"
ext_jpg = ".jpg"
ext_bmp = ".bmp"
img = cv.imread(path + file + ext_jpg)
img = cv.resize(img, (target_width, target_height))
cv.imwrite(path + file + ext_bmp, img)
cv.imshow("img", img)
cv.waitKey(0)
cv.destoryAllWindows()
py_cv_batch_resize.py, resize in batch.
It's used to prepare bmp images in my next "Adafruit_GFX/ImageReader exercises to load bmp images from MicroSD and display on 240×320 ST7789 SPI TFT, run on Seeed Studio XIAO ESP32S3 Sense (Arduino Platform)".
# Python exercise to batch resize jpg(s) and save in bmp(s)
# tested on Raspberry Pi 5/64 bit Raspberry Pi OS (bookworm)
import cv2 as cv
import glob
import os
target_width = 240
target_height = 240
src_dir = "./images"
target_subdir = src_dir + "_" + str(target_width)
print(target_subdir)
jpgfiles = []
print("Create directory:", target_subdir, "if not exist")
try:
os.mkdir(target_subdir)
print(target_subdir + " created")
except FileExistsError:
print(target_subdir + " existed")
for srcfile in glob.glob(src_dir + "/*.jpg"):
jpgfiles.append(srcfile)
print(type(srcfile), srcfile)
head, tail = os.path.split(srcfile)
dest_file = head+"_" + str(target_width) + "/" + tail[:-3] + "bmp" # save as ./images_240/*.bmp"
print(dest_file)
img = cv.imread(srcfile)
img = cv.resize(img, (target_width, target_height))
cv.imwrite(dest_file, img)
Related:
~ Install OpenCV & matplotlib on Raspberry Pi OS (Bookworm)
Comments
Post a Comment