Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting PNG to JPG in python

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()
like image 504
E K Avatar asked Feb 03 '20 22:02

E K


3 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])
like image 199
nathancy Avatar answered Oct 07 '22 15:10

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.

like image 42
skywalker Avatar answered Oct 07 '22 15:10

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
    
like image 1
vasiliyx Avatar answered Oct 07 '22 15:10

vasiliyx