How to Change Image File Extension

In Python OpenCV Tutorial, we are going to change the image file extension from one form to another using  cv2.imwrite() function. Like JPG to PNG or PNG to JPG.

Change Image File Format

Supported Image file format by OpenCV

Opencv Support Below Image file format to read & write(Save):

Windows bitmaps – *.bmp, *.dib (always supported)
JPEG files – *.jpeg, *.jpg, *.jpe (see the Notes section)
JPEG 2000 files – *.jp2 (see the Notes section)
Portable Network Graphics – *.png (see the Notes section)
Portable image format – *.pbm, *.pgm, *.ppm (always supported)
Sun rasters – *.sr, *.ras (always supported)
TIFF files – *.tiff, *.tif (see the Notes section)

Read Image

# Import Libraries
import cv2

## Read Image
#img_path = r"data/pexels-bess-hamiti-35188.jpg"
img_path = r"data/girl_face.png"
img = cv2.imread(img_path)
#img = cv2.resize(img, (1280,720))

cv2.imshow("Image", img)

cv2.waitKey(0)
cv2.destroyAllWindows()

Change Image extension JPG to PNG

img_output_path = r"data/output/girl_boy.png"
responce = cv2.imwrite(img_output_path, img)

if responce:
    print("image stored at location: ",img_output_path)

Change Image extension PNG to JPG

img_output_path = r"data/output/girl_model.jpg"
responce = cv2.imwrite(img_output_path, img)

if responce:
    print("image stored at location: ",img_output_path)

Change Image Extension from any format to another Format

img_output_path = r"data/output/girl_model_tiff.tiff"
responce = cv2.imwrite(img_output_path, img)

if responce:
    print("image stored at location: ",img_output_path)

Leave a Reply