简体   繁体   中英

Why isn't this simple python script using openCV working?

So I found a python script that I think would be extremely useful to me. It allegedly will sort photos into "blury" or "not blurry" folders.

I'm very much a python newb, but I managed in still python 3.7, numpy, and openCV. I put the script in a folder with a bunch of.jpg images and run it by typing in the command prompt:

python C:\Users\myName\images\BlurDetection.py

When I run it though it just immediately returns:

Done. Processed 0 files into 0 blurred, and 0 ok.

No error messages or anything. It just doesn't do what it's supposed to do.

Here's the script.

#
# Sorts pictures in current directory into two subdirs, blurred and ok
#

import os
import shutil
import cv2

FOCUS_THRESHOLD = 80
BLURRED_DIR = 'blurred'
OK_DIR = 'ok'

blur_count = 0
files = [f for f in os.listdir('.') if f.endswith('.jpg')]

try:
   os.makedirs(BLURRED_DIR)
   os.makedirs(OK_DIR)
except:
   pass

for infile in files:

   print('Processing file %s ...' % (infile))
   cv_image = cv2.imread(infile)

   # Covert to grayscale
   gray = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY)

   # Compute the Laplacian of the image and then the focus
   #     measure is simply the variance of the Laplacian
   variance_of_laplacian = cv2.Laplacian(gray, cv2.CV_64F).var()

   # If below threshold, it's blurry
   if variance_of_laplacian < FOCUS_THRESHOLD:
      shutil.move(infile, BLURRED_DIR)
      blur_count += 1
   else:
      shutil.move(infile, OK_DIR)

print('Done.  Processed %d files into %d blurred, and %d ok.' % (len(files), blur_count, len(files)-blur_count))

Any thoughts why it might not be working or what is wrong? Please advise. Thanks!!

Your script and photos are here:

C:\Users\myName\images

But that is not your working directory , ie Python looks for your photos in whatever this returns to you:

print(os.getcwd())

To make Python look for the files in the right folder, simply do:

os.chdir('C:\Users\myName\images')

Now it will be able to hit the files.

If.jpg images are already present in the directory then please check for folders "blurred" and "ok" in the directory. The error could be because these two folders are already present in the listed directory. I ran this code and it worked for me but when i re-ran this code without deleting the blurred and ok folder, I got the same error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM