-6

can somebody help to modify the below code so that it can run multiple images in a loop from a given folder? the code is just for a single image. Thank you.

import cv2

img = cv2.imread('6.jpg')

hieght, width = img.shape[:2]

start_row, start_col = int(hieght*0), int(width*0)
end_row, end_col = int(hieght*1), int(width*.5)

cropped = img[start_row: end_row, start_col:end_col]

cv2.imshow('Original', img)
cv2.waitKey(0)

cv2.imshow('Cropped', cropped)
cv2.waitKey(0)

cv2.destroyAllWindows()
Mike Scotty
  • 10,530
  • 5
  • 38
  • 50
  • 4
    Possible duplicate of [How can I iterate over files in a given directory?](https://stackoverflow.com/questions/10377998/how-can-i-iterate-over-files-in-a-given-directory) – Mike Scotty Apr 18 '19 at 06:04
  • Use `glob`: https://docs.python.org/3/library/glob.html – rdas Apr 18 '19 at 06:09

1 Answers1

1

Using glob:

import cv2

import glob
images = glob.glob("D:\\dirtybit\\Pictures\\*")      # get all the images
# print(images)

for img in images:
    img = cv2.imread(img)

    hieght, width = img.shape[:2]

    start_row, start_col = int(hieght*0), int(width*0)
    end_row, end_col = int(hieght*1), int(width*.5)

    cropped = img[start_row: end_row, start_col:end_col]

    cv2.imshow('Original', img)
    cv2.waitKey(0)

    cv2.imshow('Cropped', cropped)
    cv2.waitKey(0)

    cv2.destroyAllWindows()

Using os.listdir(path):

import cv2

import os
images = os.listdir("D:\\dirtybit\\Pictures\\*")

for img in images:
    img = os.path.abspath(img)
    img = cv2.imread(img)

    hieght, width = img.shape[:2]

    start_row, start_col = int(hieght*0), int(width*0)
    end_row, end_col = int(hieght*1), int(width*.5)

    cropped = img[start_row: end_row, start_col:end_col]

    cv2.imshow('Original', img)
    cv2.waitKey(0)

    cv2.imshow('Cropped', cropped)
    cv2.waitKey(0)

    cv2.destroyAllWindows()
DirtyBit
  • 16,613
  • 4
  • 34
  • 55