How to convert an image (.jpg format) to .cvs file?

How can I convert image file to csv file, is there any function or something or any other method?

I have the required image but I don’t know how to convert it into csv with three column (r,g,b)

Hello @utkarsh.sinha116,

Happy to have you in the community. :slightly_smiling_face:

Converting an image to csv is pretty straightforward. If you need columns as RGB, this code here will work for you.

import cv2
import pandas as pd
import numpy as np

im = cv2.imread("path_to_image.jpg")
b, g, r = im[:,:,0].flatten(), im[:,:,1].flatten(), im[:,:,2].flatten() #remember opencv works in BGR format

df = pd.DataFrame(np.stack([r,g,b], axis=1), columns=["R","G","B"])
df.to_csv("path_to_save_csv.csv")

The code here converts each image to a csv. But if you are looking for something like the MNIST csv file. Then you might need to convert the RGB images to grayscale and keep the m*n length vector as row for the dataframe or keep 3 csvs for R, G and B channels.

Happy Learning :smile:

1 Like

withBorder

I am getting this image as a solution for this task, I want to know what is the problem with this picture. Result is showing that it is only 40% correct to the original picture, even I interchanged the R and B column to check if that is the problem even then I am not getting any good result. Can you please tell me where is the problem?

Hello @utkarsh.sinha116,

Were you able to solve the issue?