why do I get an error when writing sys.argv[1] - python

import sys
import pygame
import random
#command line
image = sys.argv[1]
#loading the image and importing
inputImage = pygame.image.load(image)
#getting the image's height and width
(width,height) = inputImage.get_size()
#creating the bigger windom of the image by multiplying original size by 6
window = pygame.display.set_mode((width*6,height*6))
for x in range(height):
for y in range(width):
#rgb coordinates in the x and y image
(r,g,b,_) = inputImage.get_at((x,y))
#Calculate required number of circles
n1 = int(r/5)
n2 = int(g/5)
n3 = int(b/5)
#drawing random red circles on the image
while(n1 > 0):
pygame.draw.circle(window,(255,0,0),(random.randint((x*5)-15,(x*5)),random.randint((y*5)-15,(y*5))),1)
n1 = n1-1
#drawing random green circles on the image
while(n2 > 0):
pygame.draw.circle(window,(0,255,0),(random.randint((x*5)-15,(x*5)),random.randint((y*5)-15,(y*5))),1)
n2= n2-1
#drawing random blue circles on the image
while(n3 > 0):
pygame.draw.circle(window,(0,0,255),(random.randint((x*5)-15,(x*5)),random.randint((y*5)-15,(y*5))),1)
n3 = n3-1
#updating the image
pygame.display.update()
pygame.time.delay(5000)
My code sends me an error saying what the title is, so when I try to change the sys.argv line into
image = sys.argv[0]
It gives me a different error saying: pygame.error: Unsupported image format and I am not sure what that means? Am I missing something important?
Also, if you guys can help me as to how to show the pygame window after fixing the code will much appreciated :)

This method does not catch any user errors (which is what you're experiencing).
#command line
image = sys.argv[1]
You need to check a few things here:
Does the sys.argv list actually have a second element (at index [1]).
Test the filename specified actually exists.
Use a try, except block to catch any errors loading the image.
import os.path
# See if we can load the user's image
inputImage = None
if ( len( sys.argv ) >= 1 ):
image_filename = sys.argv[1]
if ( not os.path.exists( image_filename ) ):
sys.stderr.write( "Filename [" + image_filename + "] does not exist\n" )
else:
try:
inputImage = pygame.image.load( image_filename )
except:
sys.stderr.write( "Failed to load [" + image_filename + "] is it an image?\n" )
inputImage = None
else:
sys.stderr.write( "No Image Filename argument specified\n" )
### inputImage is either a valid image, or None

Related

Can I know what this error means and how to resolve this? [duplicate]

This question already has an answer here:
UnboundLocalError: local variable 'image' referenced before assignment
(1 answer)
Closed 4 months ago.
So uh I'm a new python learner trynna make an ASCII image converter..
So I wrote a code that I got off from youtube and it's giving me errors..
I reviewed the video and everything's fine
Heres the code
#note: READ THIS OR WONT WORK
#bassically to make this work you need to place this piece o code inside the same folder as your image thats being converted
#then run the code and write the file name and extension name (.jpg, .png, etc.)
#should run..
#the ascii import
import PIL.Image
#things to build the output image
#can be changed but this variety is decent
ASCII_CHARS = ["#", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."]
#resizing image
#pretty confusing but just keep this piece
def resize_image(image, new_width=100):
width, height = image.size
ratio = height / width
new_height = int(new_width * ratio)
resized_image = image.resize((new_width, new_height))
return(resized_image)
#making stuff grayscale
#this is done cus ASCII dont got any integerated colour thing
#defining the graying variable and then applying it to the image
def grayify(image):
grayscale_image = image.convert("L")
return(grayscale_image)
#make the pixels the ASCII combination mentioned above (mixture of #'s and $'s and whatever)
def pixels_to_ascii(image):
pixels = image.getdara()
characters = "".join([ASCII_CHARS[pixel//25] for pixel in pixels])
return(characters)
def main(new_width=100):
#opening source image
path = input ("Enter pathname for image:\n")
try:
image = PIL.Image.open(path)
#if no pathname found
except:
print(path, "isnt a valid pathname, try another one bro")
#define the image to make it gray then resize the gray output
new_image_data = pixels_to_ascii(grayify(resize_image(image)))
#formattin'
pixel_count = len(new_image_data)
#'ascii_image' is the head of everything where all grayscales and widths and ratios and whatnot is connected
ascii_image = "\n".join(new_image_data[i:(i+new_width)] for i in range(0, pixel_count, new_width))
#printing!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
print(ascii_image)
#save result
with open("ascii_image.txt", "w") as f:
f.write(ascii_image)
main()
And here's the errors
Traceback (most recent call last):
File "C:\Users\user\PycharmProjects\pythonProject\random\ASCII.py", line 59, in <module>
main()
File "C:\Users\user\PycharmProjects\pythonProject\random\ASCII.py", line 46, in main
new_image_data = pixels_to_ascii(grayify(resize_image(image)))
UnboundLocalError: local variable 'image' referenced before assignment
Process finished with exit code 1
So i wanna know whats wrong and what these errors means
If image = PIL.Image.open(path) generates an exception, then the variable image is never assigned a value. Then, you get the error when you try to reference it here: new_image_data = pixels_to_ascii(grayify(resize_image(image))).
You need to update your except clause to either exit the program or assign another value to image.
Which means python looking for variable called image & It's not found...You alredy decleraed image var in try block...But, Some how code not enetering into Try block...Try moving code below except and move code to try block
#note: READ THIS OR WONT WORK
#bassically to make this work you need to place this piece o code inside the same folder as your image thats being converted
#then run the code and write the file name and extension name (.jpg, .png, etc.)
#should run..
#the ascii import
import PIL.Image
#things to build the output image
#can be changed but this variety is decent
ASCII_CHARS = ["#", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."]
#resizing image
#pretty confusing but just keep this piece
def resize_image(image, new_width=100):
width, height = image.size
ratio = height / width
new_height = int(new_width * ratio)
resized_image = image.resize((new_width, new_height))
return(resized_image)
#making stuff grayscale
#this is done cus ASCII dont got any integerated colour thing
#defining the graying variable and then applying it to the image
def grayify(image):
grayscale_image = image.convert("L")
return(grayscale_image)
#make the pixels the ASCII combination mentioned above (mixture of #'s and $'s and whatever)
def pixels_to_ascii(image):
pixels = image.getdara()
characters = "".join([ASCII_CHARS[pixel//25] for pixel in pixels])
return(characters)
def main(new_width=100):
#opening source image
path = input ("Enter pathname for image:\n")
try:
image = PIL.Image.open(path)
#define the image to make it gray then resize the gray output
new_image_data = pixels_to_ascii(grayify(resize_image(image)))
#formattin'
pixel_count = len(new_image_data)
#'ascii_image' is the head of everything where all grayscales and widths and ratios and whatnot is connected
ascii_image = "\n".join(new_image_data[i:(i+new_width)] for i in range(0, pixel_count, new_width))
#printing!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
print(ascii_image)
#save result
with open("ascii_image.txt", "w") as f:
f.write(ascii_image)
#if no pathname found
except:
print(path, "isnt a valid pathname, try another one bro")
main()
First of all there is a wrong space between your input function and its argument. Secondly you should consider rewriting your try/except clause as you will run into errors when except is run due to the missing definition of the image variable.

Add a forEach or foor loop in python code

I am using this library midi2img to generate midi from images
From this library, this is the file am using:
from PIL import Image
import numpy as np
from music21 import instrument, note, chord, stream
lowerBoundNote = 21
def column2notes(column):
notes = []
for i in range(len(column)):
if column[i] > 255/2:
notes.append(i+lowerBoundNote)
return notes
resolution = 0.25
def updateNotes(newNotes,prevNotes):
res = {}
for note in newNotes:
if note in prevNotes:
res[note] = prevNotes[note] + resolution
else:
res[note] = resolution
return res
def image2midi(image_path):
with Image.open(image_path) as image:
im_arr = np.fromstring(image.tobytes(), dtype=np.uint8)
try:
im_arr = im_arr.reshape((image.size[1], image.size[0]))
except:
im_arr = im_arr.reshape((image.size[1], image.size[0],3))
im_arr = np.dot(im_arr, [0.33, 0.33, 0.33])
""" convert the output from the prediction to notes and create a midi file
from the notes """
offset = 0
output_notes = []
# create note and chord objects based on the values generated by the model
prev_notes = updateNotes(im_arr.T[0,:],{})
for column in im_arr.T[1:,:]:
notes = column2notes(column)
# pattern is a chord
notes_in_chord = notes
old_notes = prev_notes.keys()
for old_note in old_notes:
if not old_note in notes_in_chord:
new_note = note.Note(old_note,quarterLength=prev_notes[old_note])
new_note.storedInstrument = instrument.Piano()
if offset - prev_notes[old_note] >= 0:
new_note.offset = offset - prev_notes[old_note]
output_notes.append(new_note)
elif offset == 0:
new_note.offset = offset
output_notes.append(new_note)
else:
print(offset,prev_notes[old_note],old_note)
prev_notes = updateNotes(notes_in_chord,prev_notes)
# increase offset each iteration so that notes do not stack
offset += resolution
for old_note in prev_notes.keys():
new_note = note.Note(old_note,quarterLength=prev_notes[old_note])
new_note.storedInstrument = instrument.Piano()
new_note.offset = offset - prev_notes[old_note]
output_notes.append(new_note)
prev_notes = updateNotes(notes_in_chord,prev_notes)
midi_stream = stream.Stream(output_notes)
midi_stream.write('midi', fp=image_path.split("/")[-1].replace(".jpeg",".mid"))
import sys
image_path = sys.argv[1]
image2midi(image_path)
and this is the code I execute in terminal to geneate midi from image:
python img2midi.py samples/image.png
I need to make the above code to loop over all input images I put inside samples folder and generate midi for each, not just one file at a time.
Any help would be much appreciated.
You can do this by getting list of images from directory and iterate over them.
import sys
import os
sample_folder_path = sys.argv[1]
images = os.listdir(sample_folder_path) # getting all images stored in sample folder
images_path = [os.path.abspath(f"{sample_folder_path}/{image}") for image in images] # gets absolute path for all images
for image_path in images_path:
image2midi(image_path)
Usage:
python img2midi.py folder_path
Here folder_path is the path of folder that contains images. It can

SLURM batch script doesn't execute Python script, returns no error message and doesn't stop running

In a SLURM cluster I am submitting a shell script that calls a python script (both scripts can be found below. When the shell script executes it get until where the python script is called but then nothing happens: there is no output, no error message and the SLURM job keeps running.
I assume the entire contents of the python script are not relevant (but I included it anyway for completion). For debugging purposes I inserted the print("script started") line at the very beginning to see if it gets run but it doesn't. The last thing I see in the output is moved to directory.
I tried calling a test.py script containing print("test")right before this and it gets executed normally.
What could be the reason the python script doesn't start and how can I fix it?
Edit: As user jakub recommended changing print("script started")to print("script started", flush=True)successfully gets printed. Including several more of these statements revealed that the script was actually running perfectly fine, it just didn't output anything. Including the same statement within the for loop that gets constantly executed also makes all print() statements previously missing get printed.
The question then turns into: why do the print() statements here need to have flush=True in this script but not in other scripts?
Shell script:
#!/bin/bash
#SBATCH --mail-user=lukas.baehler#pathology.unibe.ch
#SBATCH --mail-type=end,fail
#SBATCH --output=out-ncl
#SBATCH --error=err-ncl
#SBATCH --job-name="Mask RCNN nucleus training and detection"
#SBATCH --time=24:00:00
#SBATCH --partition=gpu
#SBATCH --mem-per-cpu=64G
#SBATCH --gres=gpu:gtx1080ti:1
#SBATCH --constraint=rtx2080
conda init bash
source ~/.bashrc
conda activate nucl
cd MRCNN/samples/nucleus
echo "moved to directory"
python nucleus-pipeline2.py splitTMA
echo "Split TMAs"
Python script:
print("script started")
if __name__ == '__main__':
import argparse
import os
# Copied from later in script because the argparse part was moved up and is
# needed as default in --logs.
ROOT_DIR = os.path.abspath("../../")
DEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, "logs")
# Parse command line arguments
parser = argparse.ArgumentParser(
description='Mask R-CNN for nuclei counting and segmentation')
parser.add_argument("command",
metavar="<command>",
help="'splitTMA', 'splitSpot', 'structure', 'train' or 'detect'")
parser.add_argument('--dataset', required=False,
metavar="/path/to/dataset/",
help='Root directory of the dataset')
parser.add_argument('--weights', required=False,
metavar="/path/to/weights.h5",
help="Path to weights .h5 file or 'coco'")
parser.add_argument('--logs', required=False,
default=DEFAULT_LOGS_DIR,
metavar="/path/to/logs/",
help='Logs and checkpoints directory (default=logs/)')
parser.add_argument('--subset', required=False,
metavar="Dataset sub-directory",
help="Subset of dataset to run prediction on")
# Own arguments
parser.add_argument("--input", required=False,
metavar="path/to/input/folder",
help="Optionally specify the input directory. Should only be used with splitTMA, splitSpot and structure.")
parser.add_argument("--output", required=False,
metavar="path/to/output/folder",
help="Optionally specify the output directory. Should only be used with splitTMA, splitSpot and structure.")
args = parser.parse_args()
assert args.command in ["train", "detect", "splitTMA", "splitSpot", "structure"], "Must set command."
################################################################################
# splitTMA
################################################################################
# The original script for this is tma-spot.py
# Splits a TMA into images of its spots.
if args.command == "splitTMA":
import os
import cv2
import numpy as np
from openslide import open_slide
from matplotlib import pyplot as plt
###################
# CONFIGURATION
# Defines the level of resolution for spot recognition
level = 7 # Default 7
# Defines the level of resolution to use for the new images
newLevel = 0 # Default 0 (higest resolution)
# Defines the spot size in pixels (has to be changed if newLevel is changed)
SpotSize = 3072 # Default 3500
# # Shift values are for alignment of the two slides.
# shiftX = 445 - 10
# shiftY = -64 + 10
print("Using the following parameters:\nlevel = {}\nnewLevel = {}\nSpotSize = {}".format(level, newLevel, SpotSize))
###################
# NUCLEUS_DIR = "MRCNN/samples/nucleus"
NUCLEUS_DIR = os.path.abspath("")
os.chdir(NUCLEUS_DIR)
if args.input:
INPUT_DIR = args.input
else:
INPUT_DIR = "slides"
print("Using '{}' as input folder.".format(INPUT_DIR))
if args.output:
OUTPUT_DIR = args.output
else:
OUTPUT_DIR = "spots"
print("Using '{}' as output folder.".format(OUTPUT_DIR))
# mrxs_filenames = [filename for filename in os.listdir("slides") if filename[-5:] == ".mrxs"]
mrxs_filenames = [filename for filename in os.listdir(INPUT_DIR) if filename[-5:] == ".mrxs"]
print("\nFound {} MIRAX files.".format(len(mrxs_filenames)))
# Loop through all .mrxs files.
for filename in mrxs_filenames:
print("\nReading {}\n".format(filename))
# filename = mrxs_filenames[0]
img = open_slide("{}/{}".format(INPUT_DIR, filename))
# # Use if you want to to see the resolution of all the levels.
# for i in range(img.level_count):
# print("Level", i, "dimension", img.level_dimensions[i],"down factor",img.level_downsamples[i])
# Use the level set previously and read the slide as an RGB image.
x_img = img.read_region((0,0), level, img.level_dimensions[level])
x_img = np.array(x_img)
rgb = np.zeros_like(x_img)
rgb[x_img==0] = 255
rgba_im = cv2.add(rgb,x_img)
imgLevel = cv2.cvtColor(rgba_im,cv2.COLOR_RGBA2RGB)
# plt.imsave("./Output/level" + str(level) + ".png", imgLevel) # <---------- USE FOR DEBUGGING
# Converts the image to gray levels and applies a gussian blur.
gray = cv2.cvtColor(imgLevel, cv2.COLOR_BGR2GRAY)
gray_blur = cv2.GaussianBlur(gray, (3, 3), 0)
# cv2.imwrite( "./Output/gray.png", gray_blur) # <-------------------------- USE FOR DEBUGGING
# Use an Otsu binarization to generate a mask for where tissue is.
ret3, thresh = cv2.threshold(gray_blur, 8, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
thresh = ~thresh
cont_img = thresh.copy()
# cv2.imwrite( "spots/cd3/contour.png", cont_img) # <------------------------ USE FOR DEBUGGING
# Finds the contours of the mask generated.
contours, hierarchy = cv2.findContours(cont_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Loop through all contours
spot_nr = 0
for cnt in contours:
# Decide based on the area of the contour if it is a spot
area = cv2.contourArea(cnt)
spotInfo = []
x, y, w, h = cv2.boundingRect(cnt)
if area < 100 or area > 2000:
spotInfo.append([-1, x, y, w, h])
continue
if len(cnt) < 5:
spotInfo.append([-1, x, y, w, h])
continue
# Calculate the center of the spot
centerX = x + int(w/2)
centerY = y + int(h/2)
# Calculate how much it needs to be scaled
factorOld = img.level_downsamples[level]
factorNew = img.level_downsamples[newLevel]
# Read the spot region
spot = img.read_region((int(centerX * factorOld)-int(SpotSize/2),
int(centerY * factorOld)-int(SpotSize/2)),
newLevel, (SpotSize, SpotSize))
spot = cv2.cvtColor(np.array(spot), cv2.COLOR_RGBA2RGB)
# Create directory and save the image
if not os.path.isdir("{}/{}".format(OUTPUT_DIR, filename[:-5])):
os.makedirs("{}/{}".format(OUTPUT_DIR, filename[:-5]))
spot_name = "{0}/{1}/{1}-{2}.png".format(OUTPUT_DIR, filename[:-5],str(spot_nr).zfill(3))
plt.imsave(spot_name, spot)
spot_nr += 1
print("Spot {} saved - Center X and Y: {}, {}".format(spot_nr, centerX, centerY))
exit()
################################################################################
# splitSpot
################################################################################
# This is copied from spot-annotation.py
# Splits spots into tiles
if args.command == "splitSpot":
import os
import sys
import argparse
import re
import numpy as np
import cv2
from matplotlib import pyplot as plt
# VARIABLES
# Change the resolution of the tiles here. Note the image resolution
# must be an integer multiple of the tile resolutions (both dimensions).
tile_resolution = [768, 768]
# NUCLEUS_DIR = "MRCNN/samples/nucleus"
NUCLEUS_DIR = os.path.abspath("")
os.chdir(NUCLEUS_DIR)
if args.input:
INPUT_DIR = args.input
else:
INPUT_DIR = "spots"
print("\nUsing '{}' as input folder.".format(INPUT_DIR))
if args.output:
OUTPUT_DIR = args.output
else:
OUTPUT_DIR = "tiles"
print("Using '{}' as output folder.".format(OUTPUT_DIR))
# EXECUTION
TMA_folders = os.listdir(INPUT_DIR)
spot_names = []
spot_count = 0
for name in TMA_folders:
spot_names.append(os.listdir("{}/{}".format(INPUT_DIR, name)))
spot_count += len(spot_names[-1])
print("\nFound {} TMA folders with a total of {} spot images.".format(len(TMA_folders), spot_count))
for a, TMA in enumerate(TMA_folders):
for b, spot in enumerate(spot_names[a]):
print("TMA: {}/{} - Spot: {}/{}".format(a+1, len(TMA_folders), b+1, len(spot_names[a])), end="\r")
# Read the image
img = cv2.imread("{}/{}/{}".format(INPUT_DIR,TMA, spot))
# Calculate how many tiles will be produced
tilesX = img.shape[0]/tile_resolution[0]
tilesY = img.shape[1]/tile_resolution[1]
assert (tilesX == int(tilesX) and tilesY == int(tilesY)), "Image resolution is not an integer multiple of the tile resolution."
tilesX, tilesY = int(tilesX), int(tilesY)
# Create the np array that will hold the tiles
tiles = np.zeros([tilesY,tilesX,tile_resolution[0],tile_resolution[1],3])
# Loop through all tiles and store them in tiles
for i in range(tilesX):
for j in range(tilesY):
tiles[j,i] = img[i*tile_resolution[0]:(i+1)*tile_resolution[0],
j*tile_resolution[1]:(j+1)*tile_resolution[1]]
tiles = tiles.astype("uint8")
# print("\nImage was split into {} tiles.".format(tiles.shape[0]*tiles.shape[1]))
# Save all the tiles
for x in range(tiles.shape[0]):
for y in range(tiles.shape[1]):
# Displays progression
# print("Saving {}/{} images...".format(str(x*tiles.shape[0]+y+1),tiles.shape[0]*tiles.shape[1]), end="\r")
# Using the plt.imsave() gives alterations in color which is
# presumably bad. Using cv2.imwrite() is also ca. 10 times faster.
imdir = "{}/{}/{}".format(OUTPUT_DIR, TMA, spot[:-4])
imname = "{}-{}-{}.png".format(spot[:-4], str(x).zfill(2), str(y).zfill(2))
if not os.path.isdir(imdir):
os.makedirs(imdir)
cv2.imwrite("{}/{}".format(imdir, imname), tiles[x,y])
print("\nSaved images in {} as [spot_name]-x-y.png.".format(OUTPUT_DIR))
exit()
################################################################################
# Prepare Data Structure
################################################################################
# Adapted from prepare-data-structure.py
# Creates the data structure required for the network
if args.command == "structure":
import os
from shutil import copyfile
NUCLEUS_DIR = os.path.abspath("")
os.chdir(NUCLEUS_DIR)
# Setting input and output directories
if args.input:
INPUT_DIR = args.input
else:
INPUT_DIR = "tiles"
print("\nUsing '{}' as input folder.".format(INPUT_DIR))
if args.output:
OUTPUT_DIR = args.output
else:
OUTPUT_DIR = "data"
print("Using '{}' as output folder.".format(OUTPUT_DIR))
# Creates a list with the paths of all tiles. Also stores just the
# filename itself with and without file extension
file_names = []
for path,_,files in os.walk(INPUT_DIR):
for f in files:
file_names.append(["{}/{}".format(path, f), f, f[:-4]])
print("\nFound {} images.".format(len(file_names)))
assert file_names != [], "No images found in input folder."
# The dataset needs to be stored inside another folder (default "own_data")
subset = "own_data"
# For each file creates the appropriate sub-folders and copies the file.
skip_count = 0
for i,info in enumerate(file_names):
print("Saving {}/{} images.".format(i+1, len(file_names)), end="\r")
dirname = "{}/{}/{}/images".format(OUTPUT_DIR, subset, info[2])
try:
os.makedirs(dirname)
except:
skip_count += 1
continue
copyfile(info[0], "{}/{}".format(dirname, info[1]))
print("\n\nSaved dataset in {}/{}".format(OUTPUT_DIR, subset))
if skip_count > 0:
print("Skipped {} files because they already existed.".format(skip_count))
print("")
exit()
Python buffers stdin, stdout, and stderr by default. print() writes to stdout by default, so you will see this buffered behavior.
From https://stackoverflow.com/a/14258511/5666087 :
Python opens the stdin, -out and -error streams in a buffered mode; it'll read or write in larger chunks, keeping data in memory until a threshold is reached.
You can forcibly flush this buffer by passing flush=True to print. See the documentation for more information. If you have multiple print statements in a row, you need only use flush=True in the last one.

face recognition can't detect if image face is not on portrait

I try using face recognition from this link: face recognition
then modif the code like this, main.py:
#!/usr/bin/env python
import cgitb, cgi
cgitb.enable()
print("Content-Type: text/html;charset=utf-8")
print "Content-type:text/html\r\n\r\n"
import base64
import simplejson as json
import re
import face_recognition
import numpy as np
import io
from imageio import imread
from PIL import Image
import datetime
import os, errno
import shutil
params = cgi.FieldStorage()
now = datetime.datetime.now()
date = str(now)
date2 = date.replace(" ","")
img = params.getvalue('img')
data1 = json.loads(img)
data2 = data1['img2']['data']
numparray = data1['img1']
numparray2 = numparray.replace(" ", "+")
b=bytes(numparray2)
imgdata = base64.b64decode(b)
os.makedirs(date2)
with open(date2+"/img1.png", "wb") as f:
f.write(imgdata)
image = face_recognition.load_image_file(date2+'/img1.png')
try:
face_encode = face_recognition.face_encodings(image)[0]
#print("face_encode = ".format(face_encode))
except IndexError:
print("encode image failed")
quit()
known_faces = []
y = 1
for images in data2:
ir = images.replace(" ", "+")
ib = bytes(ir)
imagedata = base64.b64decode(ib)
x = str(y)
with open(date2+"/compare"+x+".png", "wb") as g:
g.write(imagedata)
compare = face_recognition.load_image_file(date2+"/compare"+x+".png")
try:
compare_encode = face_recognition.face_encodings(compare)[0]
#print("face_encode = ".format(face_encode))
except IndexError:
print("encode image compare failed")
quit()
known_faces.append(compare_encode)
y = y+1
results = face_recognition.face_distance(known_faces, face_encode)
datahasil = []
#hasilakhir = "{"
for i, face_distance in enumerate(results):
h = "{:.2}".format(face_distance, i)
#hasilakhir = hasilakhir+"compare{}"
datahasil.append(h)
hasilakhir = ','.join(datahasil)
shutil.rmtree(date2, ignore_errors=True)
print("{\"hasilcompare\" : \"" +hasilakhir+ "\"}")
the final result is compare between 2 image and give the score, in case photo of image is potrait compare is successfull, but when one of image is not on potrait (face not on potrait potision) or like face angle more than 90 degree, that give error message in catch encode failed..
i have try another way with face detection before sending 2 image to main.py to detect the image in face but when it can't detect faces i try to rotate the image untill the code detect face, but sometimes face detection can detect face with angle 90degree but in face recognition(main.py) still can't read the face.
code of rotate is here, rotate.py:import numpy as np
import cv2
from scipy import ndimage, misc
import os
from PIL import Image
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
for counter in range (0, 4):
img = cv2.imread('img/1.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
if(len(faces) == 1):
i = False
print ("face found")
break
else:
print("no face found")
i = False
img = Image.open("img/1.jpg")
img.rotate(90).save("img/1.jpg")
Yes, I think this is the problem with the library. I tested it on the same image. Once after rotation and once on the original image. It does not detect in the rotated image, both the face_locations and face_encodings are empty lists.

Python Image (PIL) library not resizing properly per kwargs

Here is my code:
import Image
import sys
import json
if __name__ == '__main__':
args = json.loads(sys.argv[1])
srcPath = args.get('srcPath')
image = Image.open(srcPath)
sizes = {}
for variant_name, dimensions in args.get('sizes').items():
if '%' in dimensions:
sizes[variant_name] = image.size
else:
width = int(dimensions.split('x')[0])
height = int(dimensions.split('x')[1])
widthAndHeight = (width, height)
sizes[variant_name] = widthAndHeight
for key, val in sizes.items():
imageName = key + '.' + srcPath.split('.')[1]
convertedImage = image.resize(val, Image.ANTIALIAS)
image.save(imageName)
print 'done'
And I'm calling it with:
python image.py '{"sizes":{"large":"200x150","orig":"100%x100%"},"srcPath":"/Users/bobcobb/Desktop/avocado.png"}'
If the argument 100%x100% is passed in, then I want to resize to the original size, otherwise, I want to resize to the passed in size. So the above code would generate 2 images (one original, the other 200x150).
Right now, it just saves the image as the original size for both. How can I fix this?
Your problem is that the resized image is assigned to convertedImage, but you save the original image (at the new filename).
So changing this line
image.save(imageName)
into
convertedImage.save(imageName)
solves this problem.

Categories

Resources