Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Open CV
  • scikit-image
  • pycairo
  • Pyglet
  • Python
  • Numpy
  • Pandas
  • Python Database
  • Data Analysis
  • ML Math
  • Machine Learning
  • NLP
  • Deep Learning
  • Deep Learning Interview Questions
  • ML Projects
  • ML Interview Questions
  • 100 Days of Machine Learning
Open In App
Next Article:
Append to JSON file using Python
Next article icon

Save image properties to CSV using Python

Last Updated : 03 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we are going to write python scripts to find the height, width, no. of channels in a given image file and save it into CSV format. Below is the implementation for the same using Python3. The prerequisite of this topic is that you have already installed NumPy and OpenCV.

Approach:

  • First, we will load the required libraries into the python file ( NumPy, OpenCV, etc.).
  • Create an empty CSV file with the column name only if there is no existing CSV file( Height, Width, Channels, colors, etc.). If the file data.csv does not exist then a new file will be created by the else statement.
  • Now we will use argparse() function to get the directory path of the images from the user in the command line.
  • Find the color properties using CV2. 
  • We will be using image.shape function to find out the Height, Width, Channels of the image.
  • Then we will calculate the average red, average blue, average green of the image
  • Then we will write the outputs to the csv file using writerow() function.

Below is the implementation:

Python3

# Required Libraries
from os import listdir
from os.path import isfile, join
from pathlib import Path
import numpy
import cv2
import argparse
import numpy
import csv
  
# Check whether the CSV 
# exists or not if not then create one.
my_file = Path("csv/details.csv")
  
if my_file.is_file():
    f = open(my_file, "w+")
    with open('csv/details.csv', 'a', newline='') as file:
        writer = csv.writer(file)
          
        writer.writerow(["S.No.", "Name", "Height",
                         "Width", "Channels",
                         "Avg Blue", "Avg Red",
                         "Avg Green"])
    f.close()
    pass
    
else:
    with open('csv/details.csv', 'w', newline = '') as file:
        writer = csv.writer(file)
          
        writer.writerow(["S.No.", "Name", "Height",
                         "Width", "Channels",
                         "Avg Blue", "Avg Red",
                         "Avg Green"])
  
# Argparse function to get
# the path of the image directory
ap = argparse.ArgumentParser()
  
ap.add_argument("-i", "--image", 
                required = True, 
                help = "Path to folder")
  
args = vars(ap.parse_args())
  
# Program to find the
# colors and embed in the CSV
mypath = args["image"]
  
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]
images = numpy.empty(len(onlyfiles), dtype = object)
  
for n in range(0, len(onlyfiles)):
    
    path = join(mypath,onlyfiles[n])
    images[n] = cv2.imread(join(mypath,onlyfiles[n]),
                           cv2.IMREAD_UNCHANGED)
      
    img = cv2.imread(path)
    h,w,c = img.shape
    print(h, w, c)
      
    avg_color_per_row = numpy.average(img, axis = 0)
    avg_color = numpy.average(avg_color_per_row, axis = 0)
      
    with open('csv/details.csv', 'a', newline = '') as file:
        writer = csv.writer(file)
        writer.writerow([n+1, onlyfiles[n], h, w, c, 
                         avg_color[0], avg_color[1],
                         avg_color[2]])
        file.close()
                      
                       

Output:

Usage:

  • Save this code-named main.py.
  • Shift(Key) + Right Click and Click open PowerShell window here.
python3 main.py --image /path/to/images/folder/:

CSV file output:

Generated Csv File



Next Article
Append to JSON file using Python
author
idevesh
Improve
Article Tags :
  • Python
  • OpenCV
  • python-csv
  • Python-OpenCV
Practice Tags :
  • python

Similar Reads

  • Save API data into CSV format using Python
    In this article, we are going to see how can we fetch data from API and make a CSV file of it, and then we can perform various stuff on it like applying machine learning model data analysis, etc. Sometimes we want to fetch data from our Database Api and train our machine learning model and it was ve
    6 min read
  • Convert Text File to CSV using Python Pandas
    Converting Text File to CSV using Python Pandas refers to the process of transforming a plain text file (often with data separated by spaces, tabs, or other delimiters) into a structured CSV (Comma Separated Values) file using the Python Pandas library. In this article we will walk you through multi
    2 min read
  • Append to JSON file using Python
    The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Pytho
    2 min read
  • Save user input to a Excel File in Python
    In this article, we will learn how to store user input in an excel sheet using Python, What is Excel? Excel is a spreadsheet in a computer application that is designed to add, display, analyze, organize, and manipulate data arranged in rows and columns. It is the most popular application for account
    4 min read
  • Convert PDF to CSV using Python
    Python is a high-level, general-purpose, and very popular programming language. Python programming language (the latest Python 3) is being used in web development, Machine Learning applications, along with all cutting-edge technology in Software Industry. Python Programming Language is very well sui
    2 min read
  • Writing CSV files in Python
    CSV (Comma Separated Values) is a simple file format used to store tabular data, such as spreadsheets or databases. Each line of the file represents a data record, with fields separated by commas. This format is popular due to its simplicity and wide support. Ways to Write CSV Files in PythonBelow a
    11 min read
  • Writing data from a Python List to CSV row-wise
    Comma Separated Values (CSV) files a type of a plain text document in which tabular information is structured using a particular format.  A CSV file is a bounded text format which uses a comma to separate values. The most common method to write data from a list to CSV file is the writerow() method o
    2 min read
  • Reading CSV files in Python
    A CSV (Comma Separated Values) file is a form of plain text document that uses a particular format to organize tabular information. CSV file format is a bounded text document that uses a comma to distinguish the values. Every row in the document is a data log. Each log is composed of one or more fie
    5 min read
  • How to save file with file name from user using Python?
    Prerequisites: File Handling in PythonReading and Writing to text files in Python Saving a file with the user's custom name can be achieved using python file handling concepts. Python provides inbuilt functions for working with files. The file can be saved with the user preferred name by creating a
    5 min read
  • Export Data From Mysql to Excel Sheet Using Python
    We are given a MySQL database and our task is to export the data into an excel sheet using Python. In this article, we will see how to export data from MySQL to Excel Sheets using Python. Export Data From Mysql to Excel Sheet Using PythonBelow are some of the ways by which we can export data from My
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences