簡體   English   中英

為什么這個使用 openCV 的簡單 python 腳本不起作用?

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

所以我找到了一個python 腳本,我認為它對我非常有用。 據稱,它會將照片分類到“模糊”或“不模糊”文件夾中。

我非常喜歡 python 新手,但我仍然在 python 3.7、numpy 和 Z6AB69B2A4C662A4B71EDZ4 中管理。 我將腳本放在一個包含一堆 .jpg 圖像的文件夾中,並通過在命令提示符下鍵入來運行它:

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

當我運行它時,它會立即返回:

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

沒有錯誤消息或任何東西。 它只是沒有做它應該做的事情。

這是腳本。

#
# 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))

任何想法為什么它可能不起作用或有什么問題? 請指教。 謝謝!!

你的劇本和照片在這里:

C:\Users\myName\images

但這不是您的工作目錄,即 Python 在返回給您的任何內容中查找您的照片:

print(os.getcwd())

要讓 Python 在正確的文件夾中查找文件,只需執行以下操作:

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

現在它將能夠命中文件。

如果.jpg 圖像已經存在於目錄中,那么請檢查目錄中的文件夾“blurred”和“ok”。 該錯誤可能是因為這兩個文件夾已存在於列出的目錄中。 我運行了這段代碼,它對我有用,但是當我重新運行這段代碼而不刪除 blurred and ok 文件夾時,我得到了同樣的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM