-1

I have a program that searches for objects based on color position and sharpness. I cut out a 140x140 pixel image of the found objects. But there are some images that are not this size due to some error. And my sharpness determinant always returns those that are smaller in size. My question is how can I iteratively go through a folder and delete only images that are not 140x140 pixels in size.

Miki
  • 40,887
  • 13
  • 123
  • 202
Cerberus
  • 51
  • 1
  • 1
  • 7
  • What exactly is the part you have difficulty with? – mkrieger1 May 18 '20 at 13:55
  • Do you know how to iteratively go through the folder? Do you know how to determine if the file is an image? Do you know how to determine the image's size? Do you know how to delete the file? *What exactly is the difficulty*? – Karl Knechtel May 18 '20 at 14:03

3 Answers3

2

Check out this tutorial, it helps with the iteration of files in a given directory given an extension (.jpg, .png, etc.)

Find all files in a directory with extension .txt in Python

To actually change the files, I'm not too sure, but probably something like python os.

iamanssd
  • 21
  • 1
1

This is one way among many different ways you can do this. Just make sure you test it before running any batch deletion as this will remove files without cautioning.

        import os
        import cv2

        img = cv2.imread('/absolute/path/to/your/file', cv2.IMREAD_GRAYSCALE)
        h, w = img.shape
        if(not (h == 140 and w == 140)):
            os.remove('/absolute/path/to/your/file')

As for iterating over files in a directory there's already a SO thread that poses multitude of solutions:

How can I iterate over files in a given directory?

Knight Forked
  • 1,529
  • 12
  • 14
  • Thanks. I phrased the question incorrectly, I was looking for the answer to how to examine the size of the image. – Cerberus May 18 '20 at 14:55
  • 1
    If you have no use loading image you can also use PIL: from PIL import Image img = Image.open('/absolute/path/to/your/file') w, h = img.size – Knight Forked May 18 '20 at 15:22
1
import os
import cv2

img = cv2.imread('/yourfile', cv2.IMREAD_GRAYSCALE)
h, w = img.shape
if(not (h ==  and w == 140)):
    os.remove('/absolute/path/to/your/file')
Green
  • 2,405
  • 3
  • 22
  • 46