Writing image in in directory in opensv code - python

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

Related

open image files from window explorer using python code

i recently just took up python for my research studentship (so i don't have a very strong cs background). I'm dealing with a large set of image files in many different subfolders in a big folder so I want to build a python code to search and open them.
I got introduced to os and sys libraries to play around with them. I could get the file to open but that is only when I specifically put a full dirpath for the file. I'm having trouble building a code to direct python to the right folder when I only know the folder name(i'm not sure if i'm making sense haha sorry).
My goal is to be able to type the id name of a folder containing the image in the python output so the file could be pulled out and displayed.
Any suggestions would be great! thank you so much!
You should look at the documentation for the functions we recommended you in the comments. Also, you may be interested to read some tutorials on files and directory, mainly in Python.
And look at how many questions we had to ask you to understand what you wanted to do. Provide code. Explain clearly what is your input, its type, its possible values, and what is the expected output.
Anyway, from what I understood so far, here is a proposal based on os.startfile :
import os
from pathlib import Path
# here I get the path to the desired directory from user input, but it could come from elsewhere
path_to_directory = Path(input("enter the path to the folder : "))
extension_of_interest = ".jpg"
filepaths_of_interest = []
for entry in path_to_directory.iterdir():
if entry.is_file() and entry.name.endswith(extension_of_interest):
print("match: " + str(entry))
filepaths_of_interest.append(entry)
else:
print("ignored: " + str(entry))
print("now opening ...")
for filepath_of_interest in filepaths_of_interest:
os.startfile(filepath_of_interest, "open")
when run, given the path C:/PycharmProjects/stack_oveflow/animals, it prints :
enter the path to the folder : C:/PycharmProjects/stack_oveflow/animals
ignored: C:\PycharmProjects\stack_oveflow\animals\cute fish.png
match: C:\PycharmProjects\stack_oveflow\animals\cute giraffe.jpg
match: C:\PycharmProjects\stack_oveflow\animals\cute penguin.jpg
match: C:\PycharmProjects\stack_oveflow\animals\cute_bunny.jpg
now opening ...
and the 3 jpg images have been opened with my default image viewer.
The startfile function was asked to "open" the file, but there are other possibilities described in the documentation.

Python processing 3 why is current working directory different sometimes?

I am getting this error sometimes when working on mac in Processing for Python. Seemingly for no reason, sometimes the current working directory becomes what you see in the image while other times it is the working directory of the folder the pyde file is in as it should be.
Any ideas on why this is occurring?
It's to avoid problems like these that I always try to use absolute paths. I would suggest you try something like this for file paths:
import os
# This will be the path to your .py file
FILE_PATH = os.path.dirname(os.path.abspath(__file__))
# This will be the path to your text file, if it is in the same directory as the .py
LEVELS_FILE_PATH = os.path.join(FILE_PATH, "levels.txt")
Then, instead of your current open statement you could have:
f = open(LEVELS_FILE_PATH, 'r')

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

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

How to save jpg file into a folder in python

This question seems really easy, but I could not figure that out. I want to save a jpg file. I used plt.savefig(fileName). I also create a new folder using import os and then os.mkdir('D:\Users\data'). Now, I want to put this figure into this created folder. Thanks in advance ...
Just pass the full path to savefig.
folderName = 'D:/Users/data'
os.makedirs(folderName)
plt.savefig(os.path.join(folderName, fileName))

Categories

Resources