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

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, i.e. 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.

Related

Converting PDF to JPG in Python

I am trying to convert a PDF into JPEG using Python. Below are the steps I have taken as well as the code but, firstly, here are:
Expected results: Have 1 JPEG file per page in the PDF file added into my "Output" folder.
Actual results: The code appears to run indefinitely without any JPEGS being added to the "Output" folder.
Steps taken:
Installed pdf2image via CMD (pip install pdf2image)
Installed Poppler.
Note on Poppler:
It is required to add it to PATH and I had done this in the environment variables but I kept getting the error pdf2image.exceptions.PDFInfoNotInstalledError: Unable to get page count. Is Poppler installed and in PATH?. So as a workaround, I have added the path in the code directly and I am not receiving this error any longer.
from pdf2image import convert_from_path
path = "D:/Users/<USERNAME>/Desktop/Python/DeratingTool/"
pdfname = path+"<PDFNAME>.pdf"
images = convert_from_path(pdfname, 500,poppler_path=r'C:\Program Files\Release-22.04.0-0\poppler-22.04.0\Library\bin')
output_folder_path = "D:/Users/<USERNAME>/Desktop/Python/DeratingTool/Output"
i = 1
for image in images:
image.save(output_folder_path + str(i) + "jpg", "JPEG")
i = i+1
Any ideas why this doesn't seem to be able to finish would be most welcome.
Thank you.
I actually found all of the information I needed for the desired result right in the definitions (Thank you, #RJAdriaansen for pointing me back there). The default format is set to "PPM" and can be changed to "jpeg" Below is the functioning code for my purposes:
from pdf2image import convert_from_path
path = "D:/Users/<USERNAME>/Desktop/Python/DeratingTool/"
pdfname = path+"<FILENAME>.pdf"
images = convert_from_path(
pdfname,
dpi=500,
poppler_path=r'C:\Program Files\Release-22.04.0-0\poppler-22.04.0\Library\bin',
output_folder="D:/Users/<USERNAME>/Desktop/Python/DeratingTool/Output",
fmt="jpeg",
jpegopt=None)
Thank you

How can I detect multiple images in a folder

I want to sort many face images to make good face images data. So, I want there's no blur, no multiple faces in one image in my images data.
I've tried the code, but my code just can check single image at once
image = face_recognition.load_image_file("./pictures/image.jpg")
face_locations = face_recognition.face_locations(image)
print(face_locations)
Is there any code to make my code can detect multiple images at once? I'd appreciate any answer. Thanks in advance!
There are no API calls in face_recognition, that allows loading several images in on time.
This page with the API documentation at readthedocs.
So I think you have to load the list of the images from a directory and then use it in a loop to get images objects.
This is This is great SO thread with answer how to load the list of files from directory using Python: Find all files in a directory with extension .txt in Python
I have no idea which framework or library you are using and you are not specific either.
As tags suggest I will do it in pythonic way.
Walk over the current directory and find and filter files by extension.
import os
def getfiles():
for root, dirs, files in os.walk("."):
for name in files:
yield os.path.join(root, name)
files = filter(lambda image: (image[-3:] == '.jpg' or image[-3:] == '.png'), getfiles())
# now you can loop your image detection api call.
for file in files
image = face_recognition.load_image_file(file)
face_locations = face_recognition.face_locations(image)
print(face_locations)

Writing image in in directory in opensv code

I am trying to write image in my opencv code, which is fine if i write without directory. But when I am trying to write in directory, it run but does not write in directory.
for i in xrange(3):
path = 'resultImages/result'
print os.path.join(path,str(i),'.png')
cv.imwrite(os.path.join(path,str(i),'.png'),images[i*3+2])
Anything wrong here?
I reffered OpenCV - Saving images to a particular folder of choice but no help.
The problem is due to the fact you are using ".png" as a sub directory inside the os.path.join() function
Try changing it to this:
for i in xrange(3):
path = 'resultImages/result'
print os.path.join(path,str(i) + '.png')
cv.imwrite(os.path.join(path,str(i) +'.png'),images[i*3+2])
I hope it helped

OpenCV Python - Reading pgm files

I'm trying to read a bunch of pgm files for a facial recognition project.
These files lie in an overall folder called "negative" and within the negative folder are subfolders. This portion of my script is supposed to go into all of the directories, store the filenames in an array, and store the "image file" in another array using OpenCV.
os.chdir("../negative")
dirnames = os.listdir(".")
neg_names = []
for i in dirnames:
if os.path.isdir(i):
os.chdir(i)
neg_names.append(os.listdir("."))
os.chdir("..")
face = cv2.imread(i,-1)
faces_negatives.append(face)
print faces_negatives
For some reason when it prints the array I get NONE in every index (there are 40 of them). From my understanding I should be getting binary values from this. This code works file with jpg files.
Just in case anyone else runs into this issue, I found a solution:
I figured out the issue I was having had to do with the path that I was sending into the function "imread". The full path of the file needs to be passed into the function in order for it to read properly. The issue was resolved when I entered in the full path of the image

cv2.imread fails in script, not on command line

cv2.imread("some.jpg") fails to read many different jpgs. I have checked a million different things:
Run the same exact code in a terminal - reads and opens images just fine
I checked version numbers of both python and cv2 - they are exactly the same:3.4.3 and 3.1.0.
Used complete paths to files. No difference
Images exist: I've manually opened dozens to see if there's something thing
Timing: added pauses just to make sure this wasn't a timing issue.
Checked to make sure the img/filename exists with print(os.path.exists(filename)) # prints True
Hardcoded a file path into `img = imread("gif_pos_0pW-p-wb8U4_0.jpg") # print(img)... None
filename = random.choice(filename_list)
print("reading:", filename) # prints correct/verified jpg paths
sleep(.5)
img = cv2.imread(filename)
sleep(.3)
print(img) # none
read_image = cv2.resize(img, (IMAGE_WIDTH, IMAGE_HEIGHT), 3)
img is none and the resize line fails with: OpenCV Error: Assertion failed (ssize.area() > 0) in resize, file /home/user/opencv/modules/imgproc/src/imgwarp.cpp, line 3229
This is Ubuntu 15.1 if it matters. Any thoughts on what could be causing this?
Yes, I know this question exists elsewhere. The existing answers have not helped me. I have quadruple checked everything. There seems to be something else going on.
The weirdest part is that cv2 reads the image just fine from the command line, with the same exact python and cv2 versions.
EDIT: this is a script, so I'm just doing python3 train.py.
The script might be executed as a different user, with different privileges or at a different location than executing the code on the command line.
Check existence of file in the code with os.path.isfile
provide details on the script (language) and how you start it. Is this a cron job, or an executable file? Start the script manually from the command line and only after that works create batch jobs or call it from other scripts.
Can you give examples of paths?
Does it work trying to load one single image located in the same directory, without using random.choice?)
Does the code below work with the image attached? It works for me.
import cv2
img=cv2.imread("image.jpg")
cv2.imshow('Test',img)
if cv2.waitKey(0) & 0xff == 27:
cv2.destroyAllWindows()

Categories

Resources