Monday 1 April 2019

Loop through images in python using opencv and python3

Below program resizes and converts the images into gray scale and saves the gray images in the same folder where the python program is saved

import os
import cv2
count=0
for filename in os.listdir("./"):
    if filename.endswith(".jpg"):
      count=count+1
      frame = cv2.imread(filename)
      frame = cv2.resize(frame,(60,60))
      gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
      filename=filename.replace('.jpg','')
      filename=filename+"GRAY"
      cv2.imwrite("%s.jpg" % filename ,gray)   
     
    else:
        continue

NOTE the images must be in the same folder where this python program is saved

Resized and gray scale image




Upload a folder that contains images and extract and loop through all the images extracted
import os
import cv2
from zipfile import ZipFile

filename="unpleasantimages.zip"
with ZipFile(filename,'r') as zip:
  zip.extractall()
count=0

for filename in os.listdir("./"):
    if filename.endswith(".jpg"):
      count=count+1
      frame = cv2.imread(filename)
      frame = cv2.resize(frame,(60,60))
      gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
      filename=filename.replace('.jpg','')
      filename=filename+"GRAY"
      print(filename)
      #cv2.imwrite("%s.jpg" % filename ,gray)   
     
    else:
        continue


to remove the folder  in google colab
!rm -rf foldername


filename="images.zip"
with ZipFile(filename,'r') as zip:
  zip.extractall()
count=0

for filename in os.listdir("./images/unpleasant/"):
    if filename.endswith(".jpg") or filename.endswith(".jpeg"):
      count=count+1
      frame = cv2.imread(filename)
      #frame = cv2.resize(frame,(60,60))
      #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
      filename=filename.replace('.jpg','')
      filename=filename+"GRAY"
      print(filename)
      #cv2.imwrite("%s.jpg" % filename ,gray)   
     
    else:
        continue
for filename in os.listdir("./images/pleasant/"):
    if filename.endswith(".jpg") or filename.endswith(".jpeg"):
      count=count+1
      frame = cv2.imread(filename)
      #frame = cv2.resize(frame,(60,60))
      #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
      filename=filename.replace('.jpg','')
      filename=filename+"GRAY"
      print(filename)
      #cv2.imwrite("%s.jpg" % filename ,gray)   
     
    else:
        continue

No comments:

Post a Comment