- Converting images to csv file in python
- Jpg to csv python
- Projects and Applications with NumPy
- Introduction
- Creating NumPy Array
- NumPy Array Manipulation
- Matrix in NumPy
- Operations on NumPy Array
- Reshaping NumPy Array
- Indexing NumPy Array
- Arithmetic operations on NumPyArray
- Linear Algebra in NumPy Array
- NumPy and Random Data
- Sorting and Searching in NumPy Array
- Universal Functions
- Python Convert Image (JPG, PNG) to CSV
Converting images to csv file in python
How about you convert your images to 2D numpy arrays and then write them as txt files with .csv extensions and , as delimiters?
Maybe you could use a code like following:
np.savetxt('np.csv', image, delimiter=',')
From your question, I think you want to know about numpy.flatten() . You want to add
right before your np.savetxt call. It will flatten the array to only one dimension and it should then print out as a single line.
The rest of your question is unclear bit it implies you have a directory full of jpeg images and you want a way to read through them all. So first, get a file list:
def createFileList(myDir, format='.jpg'): fileList = [] print(myDir) for root, dirs, files in os.walk(myDir, topdown=False): for name in files: if name.endswith(format): fullName = os.path.join(root, name) fileList.append(fullName) return fileList
The surround your code with a for fileName in fileList:
Edited to add complete example Note that I’ve used csv writer and changed your float64 to ints (which should be ok as pixel data is 0-255
from PIL import Image import numpy as np import sys import os import csv #Useful function def createFileList(myDir, format='.jpg'): fileList = [] print(myDir) for root, dirs, files in os.walk(myDir, topdown=False): for name in files: if name.endswith(format): fullName = os.path.join(root, name) fileList.append(fullName) return fileList # load the original image myFileList = createFileList('path/to/directory/') for file in myFileList: print(file) img_file = Image.open(file) # img_file.show() # get original image parameters. width, height = img_file.size format = img_file.format mode = img_file.mode # Make image Greyscale img_grey = img_file.convert('L') #img_grey.save('result.png') #img_grey.show() # Save Greyscale values value = np.asarray(img_grey.getdata(), dtype=np.int).reshape((img_grey.size[1], img_grey.size[0])) value = value.flatten() print(value) with open("img_pixels.csv", 'a') as f: writer = csv.writer(f) writer.writerow(value)
import numpy as np import cv2 import os IMG_DIR = '/home/kushal/Documents/opencv_tutorials/image_reading/dataset' for img in os.listdir(IMG_DIR): img_array = cv2.imread(os.path.join(IMG_DIR,img), cv2.IMREAD_GRAYSCALE) img_array = (img_array.flatten()) img_array = img_array.reshape(-1, 1).T print(img_array) with open('output.csv', 'ab') as f: np.savetxt(f, img_array, delimiter=",")
Jpg to csv python
Projects and Applications with NumPy
Introduction
Creating NumPy Array
- Numpy | Array Creation
- numpy.arange() in Python
- numpy.zeros() in Python
- Create a Numpy array filled with all ones
- numpy.linspace() in Python
- numpy.eye() in Python
- Creating a one-dimensional NumPy array
- How to create an empty and a full NumPy array?
- Create a Numpy array filled with all zeros | Python
- How to generate 2-D Gaussian array using NumPy?
- How to create a vector in Python using NumPy
- Python | Numpy fromrecords() method
NumPy Array Manipulation
- Copy and View in NumPy Array
- How to Copy NumPy array into another array?
- Appending values at the end of an NumPy array
- How to swap columns of a given NumPy array?
- Insert a new axis within a NumPy array
- numpy.hstack() in Python
- numpy.vstack() in python
- Joining NumPy Array
- Combining a one and a two-dimensional NumPy Array
- Python | Numpy np.ma.concatenate() method
- Python | Numpy dstack() method
- Splitting Arrays in NumPy
- How to compare two NumPy arrays?
- Find the union of two NumPy arrays
- Find unique rows in a NumPy array
- Python | Numpy np.unique() method
- numpy.trim_zeros() in Python
Matrix in NumPy
- Matrix manipulation in Python
- numpy matrix operations | empty() function
- numpy matrix operations | zeros() function
- numpy matrix operations | ones() function
- numpy matrix operations | eye() function
- numpy matrix operations | identity() function
- Adding and Subtracting Matrices in Python
- Matrix Multiplication in NumPy
- Numpy ndarray.dot() function | Python
- NumPy | Vector Multiplication
- How to calculate dot product of two vectors in Python?
- Multiplication of two Matrices in Single line using Numpy in Python
- Python | Numpy np.eigvals() method
- How to Calculate the determinant of a matrix using NumPy?
- Python | Numpy matrix.transpose()
- Python | Numpy matrix.var()
- Compute the inverse of a matrix using NumPy
Operations on NumPy Array
Reshaping NumPy Array
- Reshape NumPy Array
- Python | Numpy matrix.resize()
- Python | Numpy matrix.reshape()
- NumPy Array Shape
- Change the dimension of a NumPy array
- numpy.ndarray.resize() function – Python
- Flatten a Matrix in Python using NumPy
- numpy.moveaxis() function | Python
- numpy.swapaxes() function | Python
- Python | Numpy matrix.swapaxes()
- numpy.vsplit() function | Python
- numpy.hsplit() function | Python
- Numpy MaskedArray.reshape() function | Python
- Python | Numpy matrix.squeeze()
Indexing NumPy Array
Arithmetic operations on NumPyArray
Linear Algebra in NumPy Array
NumPy and Random Data
- Random sampling in numpy | ranf() function
- Random sampling in numpy | random() function
- Random sampling in numpy | random_sample() function
- Random sampling in numpy | sample() function
- Random sampling in numpy | random_integers() function
- Random sampling in numpy | randint() function
- numpy.random.choice() in Python
- How to choose elements from the list with different probability using NumPy?
- How to get weighted random choice in Python?
- numpy.random.shuffle() in python
- numpy.random.geometric() in Python
- numpy.random.permutation() in Python
Sorting and Searching in NumPy Array
Universal Functions
Python Convert Image (JPG, PNG) to CSV
Given an image as a .png or .jpeg file. How to convert it to a CSV file in Python?
Convert the image to a CSV using the following steps:
- Read the image into a PIL.Image object.
- Convert the PIL.Image object to a 3D NumPy array with the dimensions rows, columns, and RGB values.
- Convert the 3D NumPy array to a 2D list of lists by collapsing the RGB values into a single value (e.g., a string representation).
- Write the 2D list of lists to a CSV using normal file I/O in Python.
Here’s the code that applies these four steps, assuming the image is stored in a file named ‘c++.jpg’ :
from PIL import Image import numpy as np # 1. Read image img = Image.open('c++.jpg') # 2. Convert image to NumPy array arr = np.asarray(img) print(arr.shape) # (771, 771, 3) # 3. Convert 3D array to 2D list of lists lst = [] for row in arr: tmp = [] for col in row: tmp.append(str(col)) lst.append(tmp) # 4. Save list of lists to CSV with open('my_file.csv', 'w') as f: for row in lst: f.write(','.join(row) + '\n')
Note that the resulting CSV file looks like this with super long rows.
Each CSV cell (column) value is a representation of the RGB value at that specific pixel. For example, [255 255 255] represents the color white at that pixel.
For more information and some background on file I/O, check out our detailed tutorial on converting a list of lists to a CSV:
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.
Be on the Right Side of Change 🚀
- The world is changing exponentially. Disruptive technologies such as AI, crypto, and automation eliminate entire industries. 🤖
- Do you feel uncertain and afraid of being replaced by machines, leaving you without money, purpose, or value? Fear not! There a way to not merely survive but thrive in this new world!
- Finxter is here to help you stay ahead of the curve, so you can keep winning as paradigms shift.
Learning Resources 🧑💻
⭐ Boost your skills. Join our free email academy with daily emails teaching exponential with 1000+ tutorials on AI, data science, Python, freelancing, and Blockchain development!
Join the Finxter Academy and unlock access to premium courses 👑 to certify your skills in exponential technologies and programming.
New Finxter Tutorials:
Finxter Categories: