import cv2
import glob
from pathlib import Path
import os
path = "H:/TEZ/*.jpg"
path2 = "H:/TEZ/edit/"
for file in glob.glob(path):
basename = os.path.basename(file)
name = os.path.splitext(basename)
img = cv2.imread(file)
img_hsv=cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_red = np.array([0,95,50])
upper_red = np.array([2,255,255])
mask0 = cv2.inRange(img_hsv, lower_red, upper_red)
lower_red = np.array([175,95,50])
upper_red = np.array([180,255,255])
mask1 = cv2.inRange(img_hsv, lower_red, upper_red)
mask = mask0+mask1
output_img = img.copy()
output_img[np.where(mask==0)] = 0
output_hsv = img_hsv.copy()
output_hsv[np.where(mask==0)] = 0
son = cv2.cvtColor(output_hsv, cv2.COLOR_HSV2BGR)
cv2.imwrite("H:/TEZ/edit/" + name[0] + ".jpg", son)
this code work flawlessly on windows but when i try to convert these code in mac:
path = "/Users/turkerberkdonmez/Desktop/TEZ/*.jpg"
cv2.imwrite("/Users/turkerberkdonmez/Desktop/TEZ/edit2/" + name[0] + ".jpg", son)
nothing happens, what should i do?
i think glob function not work on mac like this?
I just ran into a similar issue. Full Disk Access wasn't the permissions setting I needed but it was the Files and Folder permissions that needed to be checked.
I also noticed that you are trying to access the Desktop folder which is not located in the Documents folder. I would try putting your needed files in the Documents folder.
Related
Basically, I copied and paste a script, and merged it with other script, and now the script doesn't work, it says an error "NoneType object has no attribute save"Screenshot
And here's the script:
` from PIL import Image
import PIL
import os
from glob import glob
imgs = [y for x in os.walk(".") for y in glob(os.path.join(x[0], '*.png'))]
size = 32, 32
lastdir = None
for file in imgs:
img = Image.open(file)
img = img.thumbnail(size, resample=PIL.Image.NEAREST)
file = file.replace('img', 'icon', 1)
dir = os.path.dirname(file)
try:
os.makedirs(dir)
except:
pass
if dir!=lastdir:
print(dir)
lastdir = dir
img.save(file + ".png", "PNG")`
Resize various images on various directories and save them, but the images are not saving.
The thumbnail() method modifies its object rather than returning a new one. So, this line:
img = img.thumbnail(size, resample=PIL.Image.NEAREST)
should be:
img.thumbnail(size, resample=PIL.Image.NEAREST)
I am going to resize image file which located in Desktop with set of subfolder.
I try following command and it works without rename save new.
from PIL import Image
import os, sys
import glob
root_dir='./././Desktop/python/'
def resize():
for filename in glob.iglob(root_dir + '**/*.jpg', recursive=True):
print(filename)
im = Image.open(filename)
imResize = im.resize((450,600), Image.ANTIALIAS)
imResize.save(filename , 'JPEG', quality=90)
resize()
My question is how can I add the correct command to save the renewe resized image file with append 'f + _thumbnail' + .jpg?
E.g file1 > file1_thumbnail.jpg
I tried add followings to row print(filename) but show error.
f, e = os.path.splitext(path+item)
size = im.size
ratio = float(final_size) / max(size)
new_image_size = tuple([int(x*ratio) for x in size])
im = im.resize(new_image_size, Image.ANTIALIAS)
new_im = Image.new("RGB", (final_size, final_size))
new_im.paste(im, ((final_size-new_image_size[0])//2, (final_size-new_image_size[1])//2))
new_im.save(f + 'resized.jpg', 'JPEG', quality=90)
May I know how can fix it?
Many Thanks
You can use python slicing of strings for this -
You can modify your code to -
from PIL import Image
import os, sys
import glob
root_dir='./././Desktop/python/'
def resize():
for filename in glob.iglob(root_dir + '**/*.jpg', recursive=True):
print(filename)
im = Image.open(filename)
imResize = im.resize((450,600), Image.ANTIALIAS)
filename = filename[:-4] + " _thumbnail" + filename[-4:]
imResize.save(filename , 'JPEG', quality=90)
resize()
The ".jpg" can be sliced at the end.
How can I fix the following error:
NotADirectoryError: [Errno 20] Not a directory:
'known_faces/.DS_Store'
Code
import face_recognition
import os
import cv2
import numpy as np
KNOWN_FACES = "known_faces"
UNKNOWN_FACES = "unknown_faces"
TOLERANCE = 0.6
THICKNESS = 3
MODEL = "cnn"
known_faces = []
known_names = []
for name in os.listdir(KNOWN_FACES):
for filename in os.listdir(f"{KNOWN_FACES}/{name}"):
image = face_recognition.load_image_file(f"{KNOWN_FACES}/{name}/{filename}")
encoding = face_recognition.face_encodings(image)
known_faces.append(encoding)
known_names.append(name)
print("processing unknown_faces")
for filename in os.listdir(UNKNOWN_FACES):
print(filename)
image = face_recognition.load_image_file(f"{UNKNOWN_FACES}/{filename}")
locations = face_recognition.face_locations(image, model=MODEL)
encodings = face_recognition.face_encodings(image, locations)
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
for face_encoding, face_locations in zip(encodings, locations):
results = face_recognition.compare_faces(face_encoding, known_faces, TOLERANCE)
MATCH = None
if True in results:
match = known_names[results.index(True)]
print(f"Match found: {match}")
top_left = (face_location[3], face_location[0])
bot_right = (face_location[1], face_location[2])
color = [0, 255, 0]
cv2.rectangle(image, top_left, bot_right, color, THICKNESS)
top_left = (face_location[3], face_location[0])
bot_right = (face_location[1], face_location[2] + 22)
cv2.rectangle(image, top_left, bot_right, color, cv2.FILLED)
cv2.putText(image, math, (face_location[3]+10, face_location[2])+15, cv2.FONT_HERSEY_SIMPLEX, 0.5, (200,200,200), THICKNESS)
cv2.imshow(filename, image)
cv2.waitKey(10000)
os.listdir(KNOWN_FACES) returns all the files in the KNOWN_FACES directory. In your specific case also the .DS_Store file.
You can filter the results considering only directories and excluding files such as .DS_Store.
import os
for name in os.listdir(KNOWN_FACES):
dir_path = os.path.join(KNOWN_FACES, name)
# if it's a directory
if os.path.isdir(dir_path):
for filename in os.listdir(dir_path):
# if the file is a valid file (a better way could be to check your specific extension, e.g., png)
if not filename.startswith('.'):
filepath = os.path.join(dir_path, filename)
image = face_recognition.load_image_file(filepath)
There is a file in your "known_faces" directory named .DS_Store. Since you only want to look at directories in the "known_faces" directory, you need to remove that file.
As abc has pointed out, you may just want to check that you are looking in a directory by using os.path.isdir().
I am trying to work on a Face Recognition system in Python OpenCV but I keep getting the following error
"!empty() in function 'cv::CascadeClassifier::detectMultiScale'"
This is the code that I'm using:
import cv2
import os
import numpy as np
from PIL import Image
import pickle
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
image_dir = os.path.join(BASE_DIR, "foto")
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml')
recognizer = cv2.face.LBPHFaceRecognizer_create()
current_id = 0
label_ids = {}
y_labels = []
x_train = []
for root, dirs, files in os.walk(image_dir):
for file in files:
if file.endswith("png") or file.endswith("jpg"):
path = os.path.join(root, file)
label = os.path.basename(root).replace(" ", "-").lower()
#print(label, path)
if not label in label_ids:
label_ids[label] = current_id
current_id += 1
id_ = label_ids[label]
#print(label_ids)
#y_labels.append(label) # some number
#x_train.append(path) # verify this image, turn into a NUMPY
arrray, GRAY
pil_image = Image.open(path).convert("L") # grayscale
size = (550, 550)
final_image = pil_image.resize(size, Image.ANTIALIAS)
image_array = np.array(final_image, "uint8")
#print(image_array)
faces = face_cascade.detectMultiScale(image_array, scaleFactor=1.5, minNeighbors=5)
for (x,y,w,h) in faces:
roi = image_array[y:y+h, x:x+w]
x_train.append(roi)
y_labels.append(id_)
#print(y_labels)
#print(x_train)
with open("pickles/face-labels.pickle", 'wb') as f:
pickle.dump(label_ids, f)
recognizer.train(x_train, np.array(y_labels))
recognizer.save("recognizers/face-trainner.yml")
What am I doing wrong?
You need to put the full path to the file.
Example:
face_cascade = cv2.CascadeClassifier('C:\\working_Dir\\data\\codes\\OpenCV\\classifiers\\haarcascade_frontalface_alt2.xml')
You can download these codes from the github Repo here : Face Detection with Python using OpenCV
I had the same issue, you need to add double slashes instead of single ones.
git clone https://github.com/opencv/opencv.git
faceCascade = cv2.CascadeClassifier('opencv/data/haarcascades/haarcascade_frontalface_default.xml')
you have to give full path of your haarcascade_frontalface_alt2.xml file
like this:-"C:\Python39\Lib\site-packages\cv2\data\haarcascade_frontalface_alt2.xml"
Xml file is missing.
Try to give full path directly like this.
face_cascade = cv2.CascadeClassifier('C:\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml')
more importantly the file should be in C Directory
I'm learning Python and try to use Pillow to resize images in a folder, then save them to another folder with the same filename. However, the program runs well, when I check the destination folder, there're no images...
My code is as below:
from PIL import Image
import os, glob, sys
src_path = "D:/Test_A/src/*.png"
dst_path = "D:/Test_A/dst/"
img_list = glob.glob(src_path)
for XXPNG in img_list:
fn = os.path.basename(XXPNG)
im = Image.open(XXPNG)
print(fn, im.size)
nim = im.resize((119, 119), Image.ANTIALIAS)
nim.save("dst_path","PNG")
print("Resize Done")
Please help me find my bug, or give my any advise.
Thank you very much for help and bearing my poor English.
"dst_path" with " is a normal text, not variable dst_path - so you save in file with name "dst_path".
You need dst_path without " - plus filename
nim.save(dst_path + fn, "PNG")
or with os.path.join()
nim.save(os.path.join(dst_path, name), "PNG")
Code:
from PIL import Image
import os, glob, sys
src_path = "D:/Test_A/src/*.png"
dst_path = "D:/Test_A/dst/"
img_list = glob.glob(src_path)
for fullpath in img_list:
name = os.path.basename(fullpath)
im = Image.open(fullpath)
print(name, im.size, '=>', os.path.join(dst_path, name))
nim = im.resize((119, 119), Image.ANTIALIAS)
nim.save(os.path.join(dst_path, name), "PNG")
#nim.save(dst_path + name, "PNG")
print("Resize Done")