How to convert PNG to JPG in Python?

Question:

I’m trying to compare two images, one a .png and the other a .jpg. So I need to convert the .png file to a .jpg to get closer values for SSIM. Below is the code that I’ve tried, but I’m getting this error:

AttributeError: ‘tuple’ object has no attribute ‘dtype’

image2 = imread(thisPath + caption)
image2 = io.imsave("jpgtest.jpg", (76, 59))
image2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
image2 = resize(image2, (76, 59))
imshow("is it a jpg", image2)
cv2.waitKey()
Asked By: E K

||

Answers:

Before demonstrating how to convert an image from .png to .jpg format, I want to point out that you should be consistent on the library that you use. Currently, you’re mixing scikit-image with opencv. It’s best to choose one library and stick with it instead of reading in an image with scikit and then converting to grayscale with opencv.

To convert a .png to .jpg image using OpenCV, you can use cv2.imwrite. Note with .jpg or .jpeg format, to maintain the highest quality, you must specify the quality value from [0..100] (default value is 95). Simply do this:

import cv2

# Load .png image
image = cv2.imread('image.png')

# Save .jpg image
cv2.imwrite('image.jpg', image, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
Answered By: nathancy

The function skimage.io.imsave expects you to give it a filename and an array that you want to save under that filename. For example:

skimage.io.imsave("image.jpg", image)

where image is a numpy array.

You are using it incorrectly here:

image2 = io.imsave("jpgtest.jpg", (76, 59))

you are assigning the output of the imsave function to image2 and I don’t think that is what you want to do.


You probably don’t need to convert the image to JPG because the skimage library already handles all of this conversion by itself. You usually only load the images with imread (does not matter whether they are PNG or JPG, because they are represented in a numpy array) and then perform all the necessary computations.

Answered By: skywalker

Python script to convert all .png in the folder into .jpg

import cv2 as cv
import glob
import os
import re

png_file_paths = glob.glob(r"*.png")
for i, png_file_path in enumerate(png_file_paths):
    jpg_file_path = png_file_path[:-3] + "jpg";
   
    # Load .png image
    image = cv.imread(png_file_path)

    # Save .jpg image
    cv.imwrite(jpg_file_path, image, [int(cv.IMWRITE_JPEG_QUALITY), 100])

    pass
    
Answered By: vasiliyx

Simply use opencv’s cvtColor. Assuming image read using cv2.imread(); image color channels arranged as BGR.

To convert from PNG to JPG

jpg_img = cv2.cvtColor(png_img, cv2.COLOR_RGBA2BGR)

To convert from JPG to PNG

png_img = cv2.cvtColor(jpg_img, cv2.COLOR_BGR2BGRA)
Answered By: mrHope012.