Git Product home page Git Product logo

cvlib's Introduction

Downloads PyPI

cvlib

A simple, high level, easy-to-use open source Computer Vision library for Python.

Installation

Installing dependencies

Provided the below python packages are installed, cvlib is completely pip installable.

  • OpenCV
  • TensorFlow

If you don't have them already installed, you can install through pip

pip install opencv-python tensorflow

Optional

or you can compile them from source if you want to enable optimizations for your specific hardware for better performance. If you are working with GPU, you can install tensorflow-gpu package through pip. Make sure you have the necessary Nvidia drivers installed preoperly (CUDA ToolKit, CuDNN etc).

If you are not sure, just go with the cpu-only tensorflow package.

You can also compile OpenCV from source to enable CUDA optimizations for Nvidia GPU.

Installing cvlib

pip install cvlib

To upgrade to the newest version pip install --upgrade cvlib

Optional

If you want to build cvlib from source, clone this repository and run the below commands.

git clone https://github.com/arunponnusamy/cvlib.git
cd cvlib
pip install .

Note: Compatability with Python 2.x is not officially tested.

Face detection

Detecting faces in an image is as simple as just calling the function detect_face(). It will return the bounding box corners and corresponding confidence for all the faces detected.

Example :

import cvlib as cv
faces, confidences = cv.detect_face(image)

Seriously, that's all it takes to do face detection with cvlib. Underneath it is using OpenCV's dnn module with a pre-trained caffemodel to detect faces.

To enable GPU

faces, confidences = cv.detect_face(image, enable_gpu=True)

Checkout face_detection.py in examples directory for the complete code.

Sample output :

Gender detection

Once face is detected, it can be passed on to detect_gender() function to recognize gender. It will return the labels (man, woman) and associated probabilities.

Example

label, confidence = cv.detect_gender(face)

Underneath cvlib is using an AlexNet-like model trained on Adience dataset by Gil Levi and Tal Hassner for their CVPR 2015 paper.

To enable GPU

label, confidence = cv.detect_gender(face, enable_gpu=True)

Checkout gender_detection.py in examples directory for the complete code.

Sample output :

Object detection

Detecting common objects in the scene is enabled through a single function call detect_common_objects(). It will return the bounding box co-ordinates, corrensponding labels and confidence scores for the detected objects in the image.

Example :

import cvlib as cv
from cvlib.object_detection import draw_bbox

bbox, label, conf = cv.detect_common_objects(img)

output_image = draw_bbox(img, bbox, label, conf)

Underneath it uses YOLOv4 model trained on COCO dataset capable of detecting 80 common objects in context.

To enable GPU

bbox, label, conf = cv.detect_common_objects(img, enable_gpu=True)

Checkout object_detection.py in examples directory for the complete code.

Real time object detection

YOLOv4 is actually a heavy model to run on CPU. If you are working with real time webcam / video feed and doesn't have GPU, try using tiny yolo which is a smaller version of the original YOLO model. It's significantly fast but less accurate.

bbox, label, conf = cv.detect_common_objects(img, confidence=0.25, model='yolov4-tiny')

Check out the example to learn more.

Other supported models: YOLOv3, YOLOv3-tiny.

Custom trained YOLO weights

To run inference with custom trained YOLOv3/v4 weights try the following

from cvlib.object_detection import YOLO

yolo = YOLO(weights, config, labels)
bbox, label, conf = yolo.detect_objects(img)
yolo.draw_bbox(img, bbox, label, conf)

To enable GPU

bbox, label, conf = yolo.detect_objects(img, enable_gpu=True)

Checkout the example to learn more.

Sample output :

Utils

Video to frames

get_frames( ) method can be helpful when you want to grab all the frames from a video. Just pass the path to the video, it will return all the frames in a list. Each frame in the list is a numpy array.

import cvlib as cv
frames = cv.get_frames('~/Downloads/demo.mp4')

Optionally you can pass in a directory path to save all the frames to disk.

frames = cv.get_frames('~/Downloads/demo.mp4', '~/Downloads/demo_frames/')

Creating gif

animate( ) method lets you create gif from a list of images. Just pass a list of images or path to a directory containing images and output gif name as arguments to the method, it will create a gif out of the images and save it to disk for you.

cv.animate(frames, '~/Documents/frames.gif')

Sponsor

Developing and maintaining open source projects takes a lot of time and effort. If you are getting value out of this project, consider supporting my work by simply buying me a coffee (one time or every month).

License

cvlib is released under MIT license.

Help

For bugs and feature requests, feel free to file a GitHub issue. (Make sure to check whether the issue has been filed already)

For usage related how-to questions, please create a new question on StackOverflow with the tag cvlib.

Community

Join the official Discord Server or GitHub Discussions to talk about all things cvlib.

Citation

If you find cvlib helpful in your work, please cite the following

@misc{ar2018cvlib,
  author =       {Arun Ponnusamy},
  title =        {cvlib - high level Computer Vision library for Python},
  howpublished = {\url{https://github.com/arunponnusamy/cvlib}},
  year =         {2018}
}

cvlib's People

Contributors

arunponnusamy avatar humandecoded avatar rafaelgrecco avatar wdove1 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cvlib's Issues

Couldn't install this Cvlib on Python 3.7.1 + pycharm + windows

Hi there.

I am trying to run the CVLib and its examples code in pycharm and downloading the cvlib through pip3.exe.
but I got struck while installing tensorflow.
error-
"could not find a version that satisfies the requirement tensorflow python 3.7"

could you please advise me regard this?

Enhancement: add option to specify config path

The current script assumes the yolo weights are present in the default user directory inside ~cvlib. This causes a problem if we run the script from a detached daemon. I'd like to suggest a config path which specifies the path to read the yolo configs from.

Face Detection's accuracy is very low

In am trying to detect a face in the image, which has single face. I exact copied your code. But the accuracy is very low. The length of list of faces is 7 (I dont know why its length is 7.).Moreover, see the result in the attached image. It is showing 2 rectangles on facial areas. Why it is not showing up to mark results, am I missing something?

Screenshot from 2019-03-25 15-37-20

The 'cvlib' distribution was not found and is required by the application in PyInstaller

I am using cvlib package in my python project. If I run python file in Linux command line its work fine without any error.

I want make it executable one file for Linux. I used PyInstaller packaged it. When run its throwing

The 'cvlib' distribution was not found and is required by the application

I am using :

  1. Python : 3.6

  2. PyInstaller : 3.5.

  3. Cvlib: 0.2.2

  4. Flask: 1.1.1.

face_detection.py for videos

I made a Colab ready notebook with changes to face_detection.py in examples folder if anyone is interested:

github link

Unfortunately I only know how to output as .avi

Attribute error on module cvlib

hey @arunponnusamy I installed cvlib via pip and try a simple code like

import cvlib as cv
import cv2

cap=cv2.VideoCapture("std_camera.mp4")
while True:
ret,image=cap.read()
faces, confidences = cv.detect_face(image)
print(faces)
print(confidences)
if cv2.waitKey(1) & 0xFF==ord('q'):
break
cv2.release()
cv2.destroyAllWindows()

but it has an attribute error logging module 'cvlib' has no attribute 'detect_face'

I also tried it with python3 but still got that error.

'str' object has no attribute 'shape'

When I try to use a function, do i get the error:

Traceback (most recent call last):
File "E:/python/test-object-detectie1.py", line 4, in
bbox, label, conf = cv.detect_common_objects('object_detection_input.jpg')
File "C:\Users\MyUserName\AppData\Local\Programs\Python\Python310\lib\site-packages\cvlib\object_detection.py", line 77, in detect_common_objects
Height, Width = image.shape[:2]
AttributeError: 'str' object has no attribute 'shape'

Can someone help me?

Is there a way of using face recognition?

Hi, I'm working in a project using face-recognition package but in cpu it's really slow so instead of doing the face detection with that I wanted to use this one buuut now I don't know how to compare the faces.

  • So far my code used face_recognition to load the saved faces
  • Then cvlib is used to face detection using the camera
  • And this is where I can't make it work, comparing the "saved_faces" from face_recognition and "faces" from cvlib

face_recognition.compare_faces(saved_faces, faces, tolerance)

So this is where I use the cvlib detection and compare using face_recognition but never makes a positive.
I'm really new with this, so I anyone could help me understand how to or even if I could make it work

Unable to execute object_detection

As of rather recently I am unable to use object_detection, whereas everything else seems to work rather fine.
It boils down to that error message:

Traceback (most recent call last):#################################################################################### |
  File "detector_mine.py", line 35, in <module>
    bbox, label, conf = cv.detect_common_objects(rect_img, confidence=0.75, enable_gpu=True')
  File "/home/user/.local/lib/python3.8/site-packages/cvlib/object_detection.py", line 135, in detect_common_objects
    outs = net.forward(get_output_layers(net))
  File "/home/user/.local/lib/python3.8/site-packages/cvlib/object_detection.py", line 29, in get_output_layers
    output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
  File "/home/user/.local/lib/python3.8/site-packages/cvlib/object_detection.py", line 29, in <listcomp>
    output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
IndexError: invalid index to scalar variable.

It runs fine on my old Win10/11 installation from a couple of months ago, however accessing the same script from a WSL machine on the exact same PC results in the error above. I'm also getting the same from a new macOS setup.

No face detected in image

Hello, I am doing a simple test; I take a picture with 5 faces, each in a different position, then try to detect the faces, but the "faces" list is empty.

Here is the image I used: https://drive.google.com/open?id=1v8C-SP0nsZ4aLuyLu8f3tjA7uI6JaQ2R

This is the code:

import cvlib as cv
import cv2

imgColor = cv2.imread('D:/images/rostro_poses.jpg', -1)

faces, confidences = cv.detect_face(imgColor)

for face,conf in zip(faces,confidences):

    (startX,startY) = face[0],face[1]
    (endX,endY) = face[2],face[3]

    cv2.rectangle(imgColor, (startX,startY), (endX,endY), (255,0,0), 2)
    
cv2.imshow('something', imgColor)

Thanks for the help.

How to add text as object to be detected

I have a pile of images and I want to find and exclude all images that contain any bit of text. I already used this library to exclude images containing people so I wonder how to adjust the library to add the text object as well.

I am not interested in any OCR and such, just the presence of a new bounding box with text description on it.

detect_face finds faces in the background with a greater confidence

Hey, first of all, thanks for the great lib. I've been playing around with face detection on the Mc-Master Pain Shoulder dataset to extract bounding boxes and am facing some issues.

In some cases, detect_faces returns multiple bounding boxes. No big deal, except that it gives a greater confidence to the wrongly detected background parts for no apparent reason.

bm049t2aaaff217

marchepas

Any idea why this could be happening ? Or how I can detect mishaps like this one ? If you have any idea how I can fix this let me know, I'd be glad to contribute.

Thanks

Live Face Detect

Screenshot (4)
i have write a code of Live face detect and not any error in this program but my output not show and my web cam proper work on my pc
Screenshot (3)

How to detect faces of a given persons ?

I want to find a face of given persons that are already fed using their face images

That is , if I gave a photo of obama and run a video (in videocapture) that contains Obama , then it have to draw a rectangle around the face and write a name tag in the rectange corner

I able to do this using face_recognation ilbrary but don't know how to do this using cvlib ?

No object detected

Hello,
First of all I am beginner in this field and thanks in advance.

I have just tried the same code you provided but, the picture I am getting as an output is the same is the input. there are no squares indicating objects.

The output I get is: (the arrays are empty so it seems nothing gets detected)
(base) Davids-MacBook-Pro:Object_Detection davidlopez$ cd /Users/davidlopez/Documents/Object_Detection ; env PYTHONIOENCODING=UTF-8 PYTHONUNBUFFERED=1 /anaconda3/bin/python /Users/davidlopez/.vscode/extensions/ms-python.python-2019.1.0/pythonFiles/ptvsd_launcher.py --default --client --host localhost --port 56195 /Users/davidlopez/Documents/Object_Detection/Obj_detection.py
Using TensorFlow backend.
[] [] []

my code is:

import cvlib as cv
from cvlib.object_detection import draw_bbox
import sys
import cv2

read input image

image = cv2.imread('varios1.jpg')

apply object detection

bbox, label, conf = cv.detect_common_objects(image)

print(bbox, label, conf)

draw bounding box over detected objects

out = draw_bbox(image, bbox, label, conf)

display output

press any key to close window

cv2.imshow("object_detection", out)
cv2.waitKey()

save output

cv2.imwrite("object_detection.jpg", out)

release resources

cv2.destroyAllWindows()

Could not read frame

Hi @arunponnusamy

I am trying to run object_detection_webcam.py.

[ WARN:0] videoio(MSMF): OnReadSample() is called with error status: -1072875772 [ WARN:0] videoio(MSMF): async ReadSample() call is failed with error status: -1072875772 [ WARN:1] videoio(MSMF): can't grab frame. Error: -1072875772 Could not read frame

It is unable to read the frame. Could you help me understand what went wrong?

Thanks.

Invalid bounding boxes returned occasionally

Sometimes the bounding boxes returned by the detect_faces method are invalid.
I'm having a issue where some bounding boxes have the same start and end x (zero total width) and sometimes the start_y is LARGER than end_y.

Any idea why this might be? These boxes are clearly not as intended

Error when import cvlib

I use python 3.6.2 and when i run this code import cvlib , it's has an error, i have installed all the packages recommend but it's doesn't work.

Using TensorFlow backend.
Traceback (most recent call last):
  File "/home/pocpon/anaconda/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/home/pocpon/anaconda/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/home/pocpon/anaconda/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/home/pocpon/anaconda/lib/python3.6/imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "/home/pocpon/anaconda/lib/python3.6/imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: libcudnn.so.7: cannot open shared object file: No such file or directory

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/pocpon/cvlib/cvlib/__init__.py", line 8, in <module>
    from .gender_detection import detect_gender
  File "/home/pocpon/cvlib/cvlib/gender_detection.py", line 4, in <module>
    from keras.utils import get_file
  File "/home/pocpon/anaconda/lib/python3.6/site-packages/keras/__init__.py", line 3, in <module>
    from . import utils
  File "/home/pocpon/anaconda/lib/python3.6/site-packages/keras/utils/__init__.py", line 6, in <module>
    from . import conv_utils
  File "/home/pocpon/anaconda/lib/python3.6/site-packages/keras/utils/conv_utils.py", line 9, in <module>
    from .. import backend as K
  File "/home/pocpon/anaconda/lib/python3.6/site-packages/keras/backend/__init__.py", line 89, in <module>
    from .tensorflow_backend import *
  File "/home/pocpon/anaconda/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py", line 5, in <module>
    import tensorflow as tf
  File "/home/pocpon/anaconda/lib/python3.6/site-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/home/pocpon/anaconda/lib/python3.6/site-packages/tensorflow/python/__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/home/pocpon/anaconda/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/home/pocpon/anaconda/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/home/pocpon/anaconda/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/home/pocpon/anaconda/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/home/pocpon/anaconda/lib/python3.6/imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "/home/pocpon/anaconda/lib/python3.6/imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: libcudnn.so.7: cannot open shared object file: No such file or directory


Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_problems

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.
`
```

module 'cvlib' has no attribute 'detect_face'

C:\xampp\htdocs\faceD>python cvlib.py
Using TensorFlow backend.
WARNING:tensorflow:From C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
2019-07-15 20:47:44.195976: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
WARNING:tensorflow:From C:\ProgramData\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py:3445: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version.
Instructions for updating:
Please use rate instead of keep_prob. Rate should be set to rate = 1 - keep_prob.
WARNING:tensorflow:From C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.cast instead.
Traceback (most recent call last):
File "cvlib.py", line 12, in
import cvlib as cv
File "C:\xampp\htdocs\faceD\cvlib.py", line 42, in
face, confidence = cv.detect_face(frame)
AttributeError: module 'cvlib' has no attribute 'detect_face'
[ WARN:0] terminating async callback

gender detecting all faces as male

Hello,

I am currently using your implementation against a webcam, and currently its detecting both male and female as MALE.

Is this expected?

Cheers!

library not working

I run this below code. it does not detect objects. detecting window also not working. please anyone help me

import cv2
import matplotlib.pyplot as plt
import cvlib as cv
import urllib.request
import numpy as np
from cvlib.object_detection import draw_bbox
import concurrent.futures

url='http://192.169.1.4/cam-hi.jpg'
im=None

def run1():
cv2.namedWindow("detection", cv2.WINDOW_AUTOSIZE)
while True:
img_resp=urllib.request.urlopen(url)
imgnp=np.array(bytearray(img_resp.read()),dtype=np.uint8)
im = cv2.imdecode(imgnp,-1)

    bbox, label, conf = cv.detect_common_objects(im, confidence=0.6, model="yolov3-tiny")

    print(bbox, label, conf)

    im = draw_bbox(im, bbox, label, conf)

    cv2.imshow("live transmission",im)
    key=cv2.waitKey(5)
    if key==ord('q'):
        break

cv2.destroyAllWindows()

if name == 'main':
print("started")
with concurrent.futures.ProcessPoolExecutor() as executer:
f1= executer.submit(run1)

tinyyolo

Thanks for this useful library. I'd love to see tiny yolo integration too

01 Motion Detection with Webcam.py

i tried to do 01 Motion Detection with Webcam.py but i have error. please help me
(base) C:\Users\vuhun>cd desktop

(base) C:\Users\vuhun\Desktop>Motion Detection with Webcam.py
[ WARN:0] videoio(MSMF): OnReadSample() is called with error status: -1072875855
[ WARN:0] videoio(MSMF): async ReadSample() call is failed with error status: -1072875855
[ WARN:1] videoio(MSMF): can't grab frame. Error: -1072875855
[ WARN:1] videoio(MSMF): can't grab frame. Error: -2147483638
[ WARN:1] videoio(MSMF): can't grab frame. Error: -2147483638
[ WARN:1] terminating async callback

(base) C:\Users\vuhun\Desktop>

Add requirements.txt

Add requirements.txt so that opencv-python and tensorflow is automatically installed when contributing.

yolov4

Hello, do you plan to release a version which uses the much faster yolov4?
And when could I expect it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.