1633696080
Aprenda a realizar la detección de género en rostros detectados en imágenes usando la biblioteca OpenCV en Python.
Divulgación : esta publicación puede contener enlaces de afiliados, lo que significa que cuando hace clic en los enlaces y realiza una compra, recibimos una comisión.
La predicción automática de género a partir de imágenes faciales ha llamado mucho la atención recientemente, debido a su amplia aplicación en varios problemas de análisis facial. Sin embargo, debido a las grandes variaciones de las imágenes faciales (como la variación en la iluminación, la escala y la oclusión), los modelos existentes todavía están por detrás del nivel de precisión deseado que es necesario para explotar estos modelos en aplicaciones del mundo real.
El objetivo de este tutorial es desarrollar una utilidad liviana basada en la línea de comandos, a través de módulos basados en Python, para detectar automáticamente rostros en una imagen estática y predecir el género de las personas detectadas utilizando un modelo de detección de género basado en el aprendizaje profundo.
Entran en juego los siguientes componentes:
Para el propósito de este artículo, usaremos modelos Caffe entrenados previamente, uno para la detección de rostros tomado del tutorial de detección de rostros y otro modelo para la detección de la edad. A continuación se muestra la lista de archivos necesarios para incluir en nuestro directorio de proyectos:
gender_net.caffemodel
: Es el modelo de ponderaciones previamente entrenado para la detección de género. Puedes descargarlo aquí .deploy_gender.prototxt
: es la arquitectura del modelo para el modelo de detección de género (un archivo de texto sin formato con una estructura similar a JSON que contiene todas las definiciones de la capa de la red neuronal). Consíguelo aquí .res10_300x300_ssd_iter_140000_fp16.caffemodel
: Los pesos del modelo previamente entrenados para la detección de rostros, descargue aquí .deploy.prototxt.txt
: Esta es la arquitectura del modelo para el modelo de detección de rostros, descárguelo aquí .Después de descargar los 4 archivos necesarios, colóquelos en la carpeta de pesos:
Para comenzar, instalemos OpenCV y NumPy:
$ pip install opencv-python numpy
Abra un nuevo archivo de Python y sígalo. Primero, importemos los módulos necesarios e inicialicemos las variables necesarias:
# Import Libraries
import cv2
import numpy as np
# The gender model architecture
# https://drive.google.com/open?id=1W_moLzMlGiELyPxWiYQJ9KFaXroQ_NFQ
GENDER_MODEL = 'weights/deploy_gender.prototxt'
# The gender model pre-trained weights
# https://drive.google.com/open?id=1AW3WduLk1haTVAxHOkVS_BEzel1WXQHP
GENDER_PROTO = 'weights/gender_net.caffemodel'
# Each Caffe Model impose the shape of the input image also image preprocessing is required like mean
# substraction to eliminate the effect of illunination changes
MODEL_MEAN_VALUES = (78.4263377603, 87.7689143744, 114.895847746)
# Represent the gender classes
GENDER_LIST = ['Male', 'Female']
# https://raw.githubusercontent.com/opencv/opencv/master/samples/dnn/face_detector/deploy.prototxt
FACE_PROTO = "weights/deploy.prototxt.txt"
# https://raw.githubusercontent.com/opencv/opencv_3rdparty/dnn_samples_face_detector_20180205_fp16/res10_300x300_ssd_iter_140000_fp16.caffemodel
FACE_MODEL = "weights/res10_300x300_ssd_iter_140000_fp16.caffemodel"
A continuación, carguemos nuestros modelos:
# load face Caffe model
face_net = cv2.dnn.readNetFromCaffe(FACE_PROTO, FACE_MODEL)
# Load gender prediction model
gender_net = cv2.dnn.readNetFromCaffe(GENDER_MODEL, GENDER_PROTO)
Al igual que el tutorial de detección de edad , antes de comenzar a detectar el género, necesitamos una forma de detectar rostros, la siguiente función se toma principalmente del tutorial de detección de rostros :
def get_faces(frame, confidence_threshold=0.5):
# convert the frame into a blob to be ready for NN input
blob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300), (104, 177.0, 123.0))
# set the image as input to the NN
face_net.setInput(blob)
# perform inference and get predictions
output = np.squeeze(face_net.forward())
# initialize the result list
faces = []
# Loop over the faces detected
for i in range(output.shape[0]):
confidence = output[i, 2]
if confidence > confidence_threshold:
box = output[i, 3:7] * \
np.array([frame.shape[1], frame.shape[0],
frame.shape[1], frame.shape[0]])
# convert to integers
start_x, start_y, end_x, end_y = box.astype(np.int)
# widen the box a little
start_x, start_y, end_x, end_y = start_x - \
10, start_y - 10, end_x + 10, end_y + 10
start_x = 0 if start_x < 0 else start_x
start_y = 0 if start_y < 0 else start_y
end_x = 0 if end_x < 0 else end_x
end_y = 0 if end_y < 0 else end_y
# append to our list
faces.append((start_x, start_y, end_x, end_y))
return faces
A continuación, hacer una función de utilidad para mostrar una imagen:
def display_img(title, img):
"""Displays an image on screen and maintains the output until the user presses a key"""
# Display Image on screen
cv2.imshow(title, img)
# Mantain output until user presses a key
cv2.waitKey(0)
# Destroy windows when user presses a key
cv2.destroyAllWindows()
A continuación, creemos dos funciones de utilidad, una para encontrar el tamaño de fuente adecuado para escribir en la imagen y otra para cambiar el tamaño de la imagen correctamente:
def get_optimal_font_scale(text, width):
"""Determine the optimal font scale based on the hosting frame width"""
for scale in reversed(range(0, 60, 1)):
textSize = cv2.getTextSize(text, fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=scale/10, thickness=1)
new_width = textSize[0][0]
if (new_width <= width):
return scale/10
return 1
# from: https://stackoverflow.com/questions/44650888/resize-an-image-without-distortion-opencv
def image_resize(image, width = None, height = None, inter = cv2.INTER_AREA):
# initialize the dimensions of the image to be resized and
# grab the image size
dim = None
(h, w) = image.shape[:2]
# if both the width and height are None, then return the
# original image
if width is None and height is None:
return image
# check to see if the width is None
if width is None:
# calculate the ratio of the height and construct the
# dimensions
r = height / float(h)
dim = (int(w * r), height)
# otherwise, the height is None
else:
# calculate the ratio of the width and construct the
# dimensions
r = width / float(w)
dim = (width, int(h * r))
# resize the image
return cv2.resize(image, dim, interpolation = inter)
Ahora que sabemos cómo detectar rostros, hagamos nuestra función principal para predecir el género de cada rostro detectado:
def predict_gender(input_path: str):
"""Predict the gender of the faces showing in the image"""
# Read Input Image
img = cv2.imread(input_path)
# resize the image, uncomment if you want to resize the image
# img = cv2.resize(img, (frame_width, frame_height))
# Take a copy of the initial image and resize it
frame = img.copy()
if frame.shape[1] > frame_width:
frame = image_resize(frame, width=frame_width)
# predict the faces
faces = get_faces(frame)
# Loop over the faces detected
# for idx, face in enumerate(faces):
for i, (start_x, start_y, end_x, end_y) in enumerate(faces):
face_img = frame[start_y: end_y, start_x: end_x]
# image --> Input image to preprocess before passing it through our dnn for classification.
# scale factor = After performing mean substraction we can optionally scale the image by some factor. (if 1 -> no scaling)
# size = The spatial size that the CNN expects. Options are = (224*224, 227*227 or 299*299)
# mean = mean substraction values to be substracted from every channel of the image.
# swapRB=OpenCV assumes images in BGR whereas the mean is supplied in RGB. To resolve this we set swapRB to True.
blob = cv2.dnn.blobFromImage(image=face_img, scalefactor=1.0, size=(
227, 227), mean=MODEL_MEAN_VALUES, swapRB=False, crop=False)
# Predict Gender
gender_net.setInput(blob)
gender_preds = gender_net.forward()
i = gender_preds[0].argmax()
gender = GENDER_LIST[i]
gender_confidence_score = gender_preds[0][i]
# Draw the box
label = "{}-{:.2f}%".format(gender, gender_confidence_score*100)
print(label)
yPos = start_y - 15
while yPos < 15:
yPos += 15
# get the font scale for this image size
optimal_font_scale = get_optimal_font_scale(label,((end_x-start_x)+25))
box_color = (255, 0, 0) if gender == "Male" else (147, 20, 255)
cv2.rectangle(frame, (start_x, start_y), (end_x, end_y), box_color, 2)
# Label processed image
cv2.putText(frame, label, (start_x, yPos),
cv2.FONT_HERSHEY_SIMPLEX, optimal_font_scale, box_color, 2)
# Display processed image
display_img("Gender Estimator", frame)
# uncomment if you want to save the image
# cv2.imwrite("output.jpg", frame)
# Cleanup
cv2.destroyAllWindows()
Aquí está el proceso de la predict_gender()
función:
cv2.imread()
función.frame_width
variable, no dude en editarla según sus necesidades.get_faces()
función previamente definida para detectar rostros en la imagen.Muy bien, llamemos a nuestra función ahora:
if __name__ == '__main__':
# Parsing command line arguments entered by user
import sys
predict_gender(sys.argv[1])
Simplemente usamos el módulo sys para obtener la ruta de la imagen desde la línea de comando. Probemos esto, estoy probando en esta imagen de archivo :
$ python predict_gender.py images\\pexels-karolina-grabowska-8526635.jpg
Aquí está la salida en la consola:
Female-97.36%
Female-98.34%
Y la imagen resultante:
Aquí hay otro ejemplo:
O esto:
Y ahí lo tienes, ahora tienes un código Python para detectar el género en cualquier imagen usando la biblioteca OpenCV. El modelo de género parece acertado.
Si desea utilizar su cámara web para detectar el género, consulte este código .
Consulta el código completo aquí .
Enlace: https://www.thepythoncode.com
#python #opencv
1619510796
Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.
Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is
Syntax: x = lambda arguments : expression
Now i will show you some python lambda function examples:
#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map
1626775355
No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas.
By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities.
Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly.
Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.
Robust frameworks
Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions.
Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events.
Simple to read and compose
Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building.
The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties.
Utilized by the best
Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player.
Massive community support
Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions.
Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking.
Progressive applications
Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.
The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.
Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential.
The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.
#python development services #python development company #python app development #python development #python in web development #python software development
1591743681
Learn Free how to create a virtual pen and eraser with python and OpenCV with source code and complete guide. This entire application is built fundamentally on contour detection. It can be thought of as something like closed color curves on compromises that have the same color or intensity, it’s like a blob. In this project we use color masking to get the binary mask of our target color pen, then we use the counter detection to find the location of this pen and the contour to find it.
#python #create virtual pen and eraser with opencv #create virtual pen and eraser with python opencv #programming #opencv #python opencv
1633696080
Aprenda a realizar la detección de género en rostros detectados en imágenes usando la biblioteca OpenCV en Python.
Divulgación : esta publicación puede contener enlaces de afiliados, lo que significa que cuando hace clic en los enlaces y realiza una compra, recibimos una comisión.
La predicción automática de género a partir de imágenes faciales ha llamado mucho la atención recientemente, debido a su amplia aplicación en varios problemas de análisis facial. Sin embargo, debido a las grandes variaciones de las imágenes faciales (como la variación en la iluminación, la escala y la oclusión), los modelos existentes todavía están por detrás del nivel de precisión deseado que es necesario para explotar estos modelos en aplicaciones del mundo real.
El objetivo de este tutorial es desarrollar una utilidad liviana basada en la línea de comandos, a través de módulos basados en Python, para detectar automáticamente rostros en una imagen estática y predecir el género de las personas detectadas utilizando un modelo de detección de género basado en el aprendizaje profundo.
Entran en juego los siguientes componentes:
Para el propósito de este artículo, usaremos modelos Caffe entrenados previamente, uno para la detección de rostros tomado del tutorial de detección de rostros y otro modelo para la detección de la edad. A continuación se muestra la lista de archivos necesarios para incluir en nuestro directorio de proyectos:
gender_net.caffemodel
: Es el modelo de ponderaciones previamente entrenado para la detección de género. Puedes descargarlo aquí .deploy_gender.prototxt
: es la arquitectura del modelo para el modelo de detección de género (un archivo de texto sin formato con una estructura similar a JSON que contiene todas las definiciones de la capa de la red neuronal). Consíguelo aquí .res10_300x300_ssd_iter_140000_fp16.caffemodel
: Los pesos del modelo previamente entrenados para la detección de rostros, descargue aquí .deploy.prototxt.txt
: Esta es la arquitectura del modelo para el modelo de detección de rostros, descárguelo aquí .Después de descargar los 4 archivos necesarios, colóquelos en la carpeta de pesos:
Para comenzar, instalemos OpenCV y NumPy:
$ pip install opencv-python numpy
Abra un nuevo archivo de Python y sígalo. Primero, importemos los módulos necesarios e inicialicemos las variables necesarias:
# Import Libraries
import cv2
import numpy as np
# The gender model architecture
# https://drive.google.com/open?id=1W_moLzMlGiELyPxWiYQJ9KFaXroQ_NFQ
GENDER_MODEL = 'weights/deploy_gender.prototxt'
# The gender model pre-trained weights
# https://drive.google.com/open?id=1AW3WduLk1haTVAxHOkVS_BEzel1WXQHP
GENDER_PROTO = 'weights/gender_net.caffemodel'
# Each Caffe Model impose the shape of the input image also image preprocessing is required like mean
# substraction to eliminate the effect of illunination changes
MODEL_MEAN_VALUES = (78.4263377603, 87.7689143744, 114.895847746)
# Represent the gender classes
GENDER_LIST = ['Male', 'Female']
# https://raw.githubusercontent.com/opencv/opencv/master/samples/dnn/face_detector/deploy.prototxt
FACE_PROTO = "weights/deploy.prototxt.txt"
# https://raw.githubusercontent.com/opencv/opencv_3rdparty/dnn_samples_face_detector_20180205_fp16/res10_300x300_ssd_iter_140000_fp16.caffemodel
FACE_MODEL = "weights/res10_300x300_ssd_iter_140000_fp16.caffemodel"
A continuación, carguemos nuestros modelos:
# load face Caffe model
face_net = cv2.dnn.readNetFromCaffe(FACE_PROTO, FACE_MODEL)
# Load gender prediction model
gender_net = cv2.dnn.readNetFromCaffe(GENDER_MODEL, GENDER_PROTO)
Al igual que el tutorial de detección de edad , antes de comenzar a detectar el género, necesitamos una forma de detectar rostros, la siguiente función se toma principalmente del tutorial de detección de rostros :
def get_faces(frame, confidence_threshold=0.5):
# convert the frame into a blob to be ready for NN input
blob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300), (104, 177.0, 123.0))
# set the image as input to the NN
face_net.setInput(blob)
# perform inference and get predictions
output = np.squeeze(face_net.forward())
# initialize the result list
faces = []
# Loop over the faces detected
for i in range(output.shape[0]):
confidence = output[i, 2]
if confidence > confidence_threshold:
box = output[i, 3:7] * \
np.array([frame.shape[1], frame.shape[0],
frame.shape[1], frame.shape[0]])
# convert to integers
start_x, start_y, end_x, end_y = box.astype(np.int)
# widen the box a little
start_x, start_y, end_x, end_y = start_x - \
10, start_y - 10, end_x + 10, end_y + 10
start_x = 0 if start_x < 0 else start_x
start_y = 0 if start_y < 0 else start_y
end_x = 0 if end_x < 0 else end_x
end_y = 0 if end_y < 0 else end_y
# append to our list
faces.append((start_x, start_y, end_x, end_y))
return faces
A continuación, hacer una función de utilidad para mostrar una imagen:
def display_img(title, img):
"""Displays an image on screen and maintains the output until the user presses a key"""
# Display Image on screen
cv2.imshow(title, img)
# Mantain output until user presses a key
cv2.waitKey(0)
# Destroy windows when user presses a key
cv2.destroyAllWindows()
A continuación, creemos dos funciones de utilidad, una para encontrar el tamaño de fuente adecuado para escribir en la imagen y otra para cambiar el tamaño de la imagen correctamente:
def get_optimal_font_scale(text, width):
"""Determine the optimal font scale based on the hosting frame width"""
for scale in reversed(range(0, 60, 1)):
textSize = cv2.getTextSize(text, fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=scale/10, thickness=1)
new_width = textSize[0][0]
if (new_width <= width):
return scale/10
return 1
# from: https://stackoverflow.com/questions/44650888/resize-an-image-without-distortion-opencv
def image_resize(image, width = None, height = None, inter = cv2.INTER_AREA):
# initialize the dimensions of the image to be resized and
# grab the image size
dim = None
(h, w) = image.shape[:2]
# if both the width and height are None, then return the
# original image
if width is None and height is None:
return image
# check to see if the width is None
if width is None:
# calculate the ratio of the height and construct the
# dimensions
r = height / float(h)
dim = (int(w * r), height)
# otherwise, the height is None
else:
# calculate the ratio of the width and construct the
# dimensions
r = width / float(w)
dim = (width, int(h * r))
# resize the image
return cv2.resize(image, dim, interpolation = inter)
Ahora que sabemos cómo detectar rostros, hagamos nuestra función principal para predecir el género de cada rostro detectado:
def predict_gender(input_path: str):
"""Predict the gender of the faces showing in the image"""
# Read Input Image
img = cv2.imread(input_path)
# resize the image, uncomment if you want to resize the image
# img = cv2.resize(img, (frame_width, frame_height))
# Take a copy of the initial image and resize it
frame = img.copy()
if frame.shape[1] > frame_width:
frame = image_resize(frame, width=frame_width)
# predict the faces
faces = get_faces(frame)
# Loop over the faces detected
# for idx, face in enumerate(faces):
for i, (start_x, start_y, end_x, end_y) in enumerate(faces):
face_img = frame[start_y: end_y, start_x: end_x]
# image --> Input image to preprocess before passing it through our dnn for classification.
# scale factor = After performing mean substraction we can optionally scale the image by some factor. (if 1 -> no scaling)
# size = The spatial size that the CNN expects. Options are = (224*224, 227*227 or 299*299)
# mean = mean substraction values to be substracted from every channel of the image.
# swapRB=OpenCV assumes images in BGR whereas the mean is supplied in RGB. To resolve this we set swapRB to True.
blob = cv2.dnn.blobFromImage(image=face_img, scalefactor=1.0, size=(
227, 227), mean=MODEL_MEAN_VALUES, swapRB=False, crop=False)
# Predict Gender
gender_net.setInput(blob)
gender_preds = gender_net.forward()
i = gender_preds[0].argmax()
gender = GENDER_LIST[i]
gender_confidence_score = gender_preds[0][i]
# Draw the box
label = "{}-{:.2f}%".format(gender, gender_confidence_score*100)
print(label)
yPos = start_y - 15
while yPos < 15:
yPos += 15
# get the font scale for this image size
optimal_font_scale = get_optimal_font_scale(label,((end_x-start_x)+25))
box_color = (255, 0, 0) if gender == "Male" else (147, 20, 255)
cv2.rectangle(frame, (start_x, start_y), (end_x, end_y), box_color, 2)
# Label processed image
cv2.putText(frame, label, (start_x, yPos),
cv2.FONT_HERSHEY_SIMPLEX, optimal_font_scale, box_color, 2)
# Display processed image
display_img("Gender Estimator", frame)
# uncomment if you want to save the image
# cv2.imwrite("output.jpg", frame)
# Cleanup
cv2.destroyAllWindows()
Aquí está el proceso de la predict_gender()
función:
cv2.imread()
función.frame_width
variable, no dude en editarla según sus necesidades.get_faces()
función previamente definida para detectar rostros en la imagen.Muy bien, llamemos a nuestra función ahora:
if __name__ == '__main__':
# Parsing command line arguments entered by user
import sys
predict_gender(sys.argv[1])
Simplemente usamos el módulo sys para obtener la ruta de la imagen desde la línea de comando. Probemos esto, estoy probando en esta imagen de archivo :
$ python predict_gender.py images\\pexels-karolina-grabowska-8526635.jpg
Aquí está la salida en la consola:
Female-97.36%
Female-98.34%
Y la imagen resultante:
Aquí hay otro ejemplo:
O esto:
Y ahí lo tienes, ahora tienes un código Python para detectar el género en cualquier imagen usando la biblioteca OpenCV. El modelo de género parece acertado.
Si desea utilizar su cámara web para detectar el género, consulte este código .
Consulta el código completo aquí .
Enlace: https://www.thepythoncode.com
#python #opencv
1602968400
Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?
In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.
Swapping value in Python
Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead
>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName
>>> print(FirstName, LastName)
('Jordan', 'kalebu')
#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development