Giter Club home page Giter Club logo

imutils's Introduction

imutils

A series of convenience functions to make basic image processing functions such as translation, rotation, resizing, skeletonization, and displaying Matplotlib images easier with OpenCV and both Python 2.7 and Python 3.

For more information, along with a detailed code review check out the following posts on the PyImageSearch.com blog:

Installation

Provided you already have NumPy, SciPy, Matplotlib, and OpenCV already installed, the imutils package is completely pip-installable:

$ pip install imutils

Finding function OpenCV functions by name

OpenCV can be a big, hard to navigate library, especially if you are just getting started learning computer vision and image processing. The find_function method allows you to quickly search function names across modules (and optionally sub-modules) to find the function you are looking for.

Example:

Let's find all function names that contain the text contour:

import imutils
imutils.find_function("contour")

Output:

1. contourArea
2. drawContours
3. findContours
4. isContourConvex

The contourArea function could therefore be accessed via: cv2.contourArea

Translation

Translation is the shifting of an image in either the x or y direction. To translate an image in OpenCV you would need to supply the (x, y)-shift, denoted as (tx, ty) to construct the translation matrix M:

Translation equation

And from there, you would need to apply the cv2.warpAffine function.

Instead of manually constructing the translation matrix M and calling cv2.warpAffine, you can simply make a call to the translate function of imutils.

Example:

# translate the image x=25 pixels to the right and y=75 pixels up
translated = imutils.translate(workspace, 25, -75)

Output:

Translation example

Rotation

Rotating an image in OpenCV is accomplished by making a call to cv2.getRotationMatrix2D and cv2.warpAffine. Further care has to be taken to supply the (x, y)-coordinate of the point the image is to be rotated about. These calculation calls can quickly add up and make your code bulky and less readable. The rotate function in imutils helps resolve this problem.

Example:

# loop over the angles to rotate the image
for angle in xrange(0, 360, 90):
	# rotate the image and display it
	rotated = imutils.rotate(bridge, angle=angle)
	cv2.imshow("Angle=%d" % (angle), rotated)

Output:

Rotation example

Resizing

Resizing an image in OpenCV is accomplished by calling the cv2.resize function. However, special care needs to be taken to ensure that the aspect ratio is maintained. This resize function of imutils maintains the aspect ratio and provides the keyword arguments width and height so the image can be resized to the intended width/height while (1) maintaining aspect ratio and (2) ensuring the dimensions of the image do not have to be explicitly computed by the developer.

Another optional keyword argument, inter, can be used to specify interpolation method as well.

Example:

# loop over varying widths to resize the image to
for width in (400, 300, 200, 100):
	# resize the image and display it
	resized = imutils.resize(workspace, width=width)
	cv2.imshow("Width=%dpx" % (width), resized)

Output:

Resizing example

Skeletonization

Skeletonization is the process of constructing the "topological skeleton" of an object in an image, where the object is presumed to be white on a black background. OpenCV does not provide a function to explicitly construct the skeleton, but does provide the morphological and binary functions to do so.

For convenience, the skeletonize function of imutils can be used to construct the topological skeleton of the image.

The first argument, size is the size of the structuring element kernel. An optional argument, structuring, can be used to control the structuring element -- it defaults to cv2.MORPH_RECT , but can be any valid structuring element.

Example:

# skeletonize the image
gray = cv2.cvtColor(logo, cv2.COLOR_BGR2GRAY)
skeleton = imutils.skeletonize(gray, size=(3, 3))
cv2.imshow("Skeleton", skeleton)

Output:

Skeletonization example

Displaying with Matplotlib

In the Python bindings of OpenCV, images are represented as NumPy arrays in BGR order. This works fine when using the cv2.imshow function. However, if you intend on using Matplotlib, the plt.imshow function assumes the image is in RGB order. A simple call to cv2.cvtColor will resolve this problem, or you can use the opencv2matplotlib convenience function.

Example:

# INCORRECT: show the image without converting color spaces
plt.figure("Incorrect")
plt.imshow(cactus)

# CORRECT: convert color spaces before using plt.imshow
plt.figure("Correct")
plt.imshow(imutils.opencv2matplotlib(cactus))
plt.show()

Output:

Matplotlib example

URL to Image

This the url_to_image function accepts a single parameter: the url of the image we want to download and convert to a NumPy array in OpenCV format. This function performs the download in-memory. The url_to_image function has been detailed here on the PyImageSearch blog.

Example:

url = "http://pyimagesearch.com/static/pyimagesearch_logo_github.png"
logo = imutils.url_to_image(url)
cv2.imshow("URL to Image", logo)
cv2.waitKey(0)

Output:

Matplotlib example

Checking OpenCV Versions

OpenCV 3 has finally been released! But with the major release becomes backward compatibility issues (such as with the cv2.findContours and cv2.normalize functions). If you want your OpenCV 3 code to be backwards compatible with OpenCV 2.4.X, you'll need to take special care to check which version of OpenCV is currently being used and then take appropriate action. The is_cv2() and is_cv3() are simple functions that can be used to automatically determine the OpenCV version of the current environment.

Example:

print("Your OpenCV version: {}".format(cv2.__version__))
print("Are you using OpenCV 2.X? {}".format(imutils.is_cv2()))
print("Are you using OpenCV 3.X? {}".format(imutils.is_cv3()))

Output:

Your OpenCV version: 3.0.0
Are you using OpenCV 2.X? False
Are you using OpenCV 3.X? True

Automatic Canny Edge Detection

The Canny edge detector requires two parameters when performing hysteresis. However, tuning these two parameters to obtain an optimal edge map is non-trivial, especially when working with a dataset of images. Instead, we can use the auto_canny function which uses the median of the grayscale pixel intensities to derive the upper and lower thresholds. You can read more about the auto_canny function here.

Example:

gray = cv2.cvtColor(logo, cv2.COLOR_BGR2GRAY)
edgeMap = imutils.auto_canny(gray)
cv2.imshow("Original", logo)
cv2.imshow("Automatic Edge Map", edgeMap)

Output:

Matplotlib example

4-point Perspective Transform

A common task in computer vision and image processing is to perform a 4-point perspective transform of a ROI in an image and obtain a top-down, "birds eye view" of the ROI. The perspective module takes care of this for you. A real-world example of applying a 4-point perspective transform can be bound in this blog on on building a kick-ass mobile document scanner.

Example

See the contents of demos/perspective_transform.py

Output:

Matplotlib example

Sorting Contours

The contours returned from cv2.findContours are unsorted. By using the contours module the the sort_contours function we can sort a list of contours from left-to-right, right-to-left, top-to-bottom, and bottom-to-top, respectively.

Example:

See the contents of demos/sorting_contours.py

Output:

Matplotlib example

(Recursively) Listing Paths to Images

The paths sub-module of imutils includes a function to recursively find images based on a root directory.

Example:

Assuming we are in the demos directory, let's list the contents of the ../demo_images:

from imutils import paths
for imagePath in paths.list_images("../demo_images"):
	print imagePath

Output:

../demo_images/bridge.jpg
../demo_images/cactus.jpg
../demo_images/notecard.png
../demo_images/pyimagesearch_logo.jpg
../demo_images/shapes.png
../demo_images/workspace.jpg

imutils's People

Contributors

abhitronix avatar adamspannbauer avatar andrewda avatar antocuni avatar drmacdon avatar farizrahman4u avatar jrosebr1 avatar kylehounslow avatar lukasbrchl avatar marjinal1st avatar mr2011 avatar sdadia avatar skypanther avatar timgates42 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  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

imutils's Issues

threaded frame rate slower than speficied

I have a code example, where the processing pipe's throughput is about 23 fps, while the framerate of PiVideoStream is specified to be 40. See the following code:

from __future__ import print_function
from imutils.video.pivideostream import PiVideoStream
from imutils.video import FPS
import imutils
import time
import cv2


# function to return the difference of elementsums between consecutive frames. If it returns 0, 
# then  the frames are identical with a high probability

def diff(frame1,frame2):
    return(cv2.sumElems(frame1)[0]-cv2.sumElems(frame2)[0])

vs = PiVideoStream(resolution=(720,720),framerate=40).start()
time.sleep(2.0)
fps = FPS().start()
diffs=[]
frame2 = vs.read()
while fps._numFrames < 50:
    frame1 = frame2
    time.sleep(0.025)
    frame2 = vs.read()
    diffs.append(diff(frame1,frame2))
    fps.update()


fps.stop()
print("[INFO] elasped time: {:.2f}".format(fps.elapsed()))
print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))
print(diffs)

cv2.destroyAllWindows()
vs.stop()

The script is doing the following:

comparing two consecutive frames by subtracting the elementsums of each from each other. If the result is zero, then the frames must have been identical (since the scene is not static). The for loop is looping through several frames and storing consecutive differences to 'diffs'.

Remember, according to imutils.video.FPS my throughput is 23 frames per second. Therefore if the camera framerate is 40, and the PiVideoStream is actually working like it is supposed to do, then the elements of diffs should be all non-zero. But in fact up to 40% of the elements are zero. try it out
The camera itself is surely able to handel 40fps. So there must be something with the implementation of threading.

Package importation error on perspective module

I'm experiencing trouble accessing the modules in the imutils package, running in an Anaconda virtual environment. As you'll see in the console output below, I'm in the env and the package itself imports, but none of the modules are accessible. The package was successfully installed using pip in the env, which I also include in the output.

(datasci) saturn:cvtraining eronlloyd$ pip install imutils
Collecting imutils
  Downloading https://files.pythonhosted.org/packages/15/ba/24272ac57159cf255959f9298b8e42f00528be90ce4ccd274b604ae5e32d/imutils-0.4.6.tar.gz
Building wheels for collected packages: imutils
  Running setup.py bdist_wheel for imutils ... done
  Stored in directory: /Users/eronlloyd/Library/Caches/pip/wheels/cb/58/9b/7debccbc53159611f67cc7e2e3ed37b217e56e9b40e7ba80c3
Successfully built imutils
Installing collected packages: imutils
Successfully installed imutils-0.4.6
(datasci) saturn:cvtraining eronlloyd$ ls /Users/eronlloyd/anaconda/envs/datasci/lib/python3.6/site-packages/imutils
__init__.py		face_utils		paths.py
__pycache__		feature			perspective.py
contours.py		io			video
convenience.py		meta.py
encodings.py		object_detection.py
(datasci) saturn:cvtraining eronlloyd$ ipython
Python 3.6.5 | packaged by conda-forge | (default, Apr  6 2018, 13:44:09)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import imutils

In [2]: dir(imutils)
Out[2]: 
['__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'cv2',
 'np',
 'resize',
 'rotate',
 'translate']

In [3]: from imutils import perspective
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-3-1c2f33893220> in <module>()
----> 1 from imutils import perspective

ImportError: cannot import name 'perspective'

I've seen others have basic installation issues with pip or their virtualenv, but I believe this more directly related to the package itself. Can anyone confirm successful installation in a conda env?

Pi Camera looks ineffective

I have Raspberry Pi 2 Model B and a PiNoir.
The options in VideoStream() look ineffective:

  • usePiCamera : I got a frame from the camera whther I set it True or False
  • resolution: whatever (width, height) I set, I always have a 640x480 frame.
  • framerate: always the maximum

Weird "flickering" when using VideoStream.read

I'm seeing some strange flickering (like dropping every second frame or something) when processing frames obtained through VideoStream.read() through cv2.dilate and cv2.absdiff.

Example of Working, "pure OpenCV" code: https://gist.github.com/xoxota99/dd5a3c412a7505faa7d2179e8417b517

Equivalent code, using VideoStream, causing flickering.
https://gist.github.com/xoxota99/46019b359a15e180b18db3e6f4502b57

I notice that the framerate is (obviously) much higher using VideoStream, but is there a way to avoid the dropped frames?

PiVideoStream.read() gives me worked on image????

Firstly I have a local copy of your pivideostream.py which I have amended to do 640x480
it is attached

Then I have a program which is looking at the frames
They are coming into a cam variable via vs.read()
It highlights any blue areas and the final image is stored in disp variable

The problem is that sometimes I am getting what I put out as disp back from vs.read()
You can see double green outlines sometimes in the program. Very Weird...
Have you seen this behaviour before?

You should be able to replicate if you run the attached code with my copy of pivideostream in the same directory and put something
blue under the camera

help.zip

vs.read() stuck when I rerun the script again

I use this code to read the image from Logitech C720 and save them to disk in Raspberry 3B+ Raspbian stretch.

Everything goes well when I run the script for the first time, but when I rerun the script again. It was stuck as vs.read(), and I have to cancel it by CTRL+C.

Is there anything wrong with my code?

from imutils.video import VideoStream
from imutils.video import FPS
import datetime
import imutils
import time
import cv2
import os 

os.system("mkdir record")
print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()
fps = FPS().start()


i = 0
while i < 2000:
    frame = vs.read()
    if frame is None:
        continue
    timestamp = datetime.datetime.now()
    cv2.imwrite("record/%d.jpg" % i, frame)
    print i
    fps.update()
    i += 1

fps.stop()
print("[INFO] elapsed time: {:.2f}".format(fps.elapsed()))
print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))
vs.stop()

WebcamVideoStream not releasing the camera when stopped

Hello,
It looks like the WebcamVideoStream is not releasing the VideoCapture in the stop method. So when I exit out of python the camera is not being released.
Changing the stop function like this fixed the issue for me:

class WebcamVideoStream:
....
def stop(self):
# indicate that the thread should be stopped
self.stopped = True
self.stream.release()

How to input a frame of video by using VideoStream?

Hi Adrian,
Firstly, thanks for your great works!

I want to use a video file as the input, like that: vs=cv2.VideoCapture("my_video_file.mp4") , and take one of the video file frame into the StreamVideo, by using
vs = VideoStream(frame).start()

But I got error message like that::
self.stream = WebcamVideoStream(src=src)
File "D:\Anaconda3\lib\site-packages\imutils\video\webcamvideostream.py", line 9, in init
self.stream = cv2.VideoCapture(src)
TypeError: only size-1 arrays can be converted to Python scalars

how to input the frame to the following class?
class WebcamVideoStream:###
def init(self, src):
# initialize the video camera stream and read the first frame
# from the stream
self.stream = cv2.VideoCapture(src)
Many thanks for your great work again.
hope I will get your answer
Cheers!
Edward

How to do NMS on bounding box with confidence level?

Hi, I want to do object detection and I want to apply the NMS on the bounding box.
Currently I already have the bounding box as:

'img06122.jpg': 
[(1543.76794434, 294.937072754, 1609.1029052775, 379.47564697279995, 0.9614292), 
(1547.41760254, 297.940643311, 1602.6791992197, 363.4836425786, 0.48836288), 
(483.551971436, 221.907653809, 516.4211425786, 290.0017395024, 0.42841634), 
(697.461730957, 208.688247681, 722.3622436523, 288.6661682132, 0.80467176), 
(902.461608887, 201.461975098, 940.9091796878, 248.1532287601, 0.42420116), 
(484.223114014, 235.124008179, 510.01104736359997, 299.5354919436, 0.81936955), 
(908.549377441, 195.727310181, 932.9542236324, 241.93359375030002, 0.87299836), 
(872.921203613, 200.903030396, 891.8666381833, 252.541702271, 0.85704684), 
(926.151489258, 196.695953369, 945.2242431642, 241.85830688459998, 0.41192102), 
(910.424377441, 207.047485352, 928.8771362301001, 249.7248382573, 0.4464341), 
(848.827270508, 205.648757935, 865.6982421877, 250.6044769291, 0.7687473)]

The first 4 number are x1 y1 x2 y2, the last one is the confidence level (or we could say probability)

I checked code on this blog (Faster) Non-Maximum Suppression in Python In the comments, you said that could use the prob variable for nms.

Is there a code example for this function with prob?

Also, how could we return the bounding box with float number? I do not want to cast to integer.

Thank you!

Files missing from pypi tarball

The tarball available from pypi does not contain some files that exist in the git repo:
LICENSE.txt
README.md
docs directory
demos & demo_images directories

Some are maybe not as important as others ...

Imutils seems to break a conda-forge install of opencv

I'm Running Anaconda version 3... in Ubuntu 18.04.
I found the installation of imutils caused an import error for opencv.

In a new virtual env with python=3.6 I ran:
pip install scipy numpy matplotlib pandas

Installed opencv (v )from conda-forge
conda config --add channels conda-forge
conda install opencv

This ran fine until I tried
pip install imutils

It threw the following error
ImportError: /home/dak-rambo/anaconda3/envs/cv/lib/python3.6/site-packages/../../libopencv_dnn.so.3.4: undefined symbol: _ZNK6google8protobuf7Message25InitializationErrorStringB5cxx11Ev

non-maxima suppression requires dimension 1 probs array

When I give it an array of shape (1,1, 5), for example, or whatever the output of cv2.detectMultiScale is, it sorts by something else. If I do a ravel() on it instead, it works. It would be great if you could add that to the input validation on one of the first lines. Thanks.

imutils module not found

Hi,

I'm using anaconda2 which is running Python 2.7.12. I did pip install imutils and it looks like it installed correctly, here is the result of pip show:

Name: imutils
Version: 0.4.3
Summary: A series of convenience functions to make basic image processing functi
ons such as translation, rotation, resizing, skeletonization, displaying Matplot
lib images, sorting contours, detecting edges, and much more easier with OpenCV
and both Python 2.7 and Python 3.
Home-page: https://github.com/jrosebr1/imutils
Author: Adrian Rosebrock
Author-email: [email protected]
License: UNKNOWN
Location: c:\programdata\anaconda2\lib\site-packages
Requires:

However, in anaconda if I type "import imutils" it always says no module found. Should I be using a different version of imutils? I'm not sure how to resolve this issue. Any advice of help is much appreciated. Thanks!

pip install imutils is not installing in python 2.7

C:\Python27\Scripts>pip install imutils
Collecting imutils
Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connec
tion broken by 'ConnectTimeoutError(<pip._vendor.requests.packages.urllib3.conne
ction.VerifiedHTTPSConnection object at 0x000000000391C518>, 'Connection to 10.1
.0.11 timed out. (connect timeout=15)')': /simple/imutils/
Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connec
tion broken by 'ConnectTimeoutError(<pip._vendor.requests.packages.urllib3.conne
ction.VerifiedHTTPSConnection object at 0x000000000391C1D0>, 'Connection to 10.1
.0.11 timed out. (connect timeout=15)')': /simple/imutils/
Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connec
tion broken by 'ConnectTimeoutError(<pip._vendor.requests.packages.urllib3.conne
ction.VerifiedHTTPSConnection object at 0x000000000391C0F0>, 'Connection to 10.1
.0.11 timed out. (connect timeout=15)')': /simple/imutils/
Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connec
tion broken by 'ConnectTimeoutError(<pip._vendor.requests.packages.urllib3.conne
ction.VerifiedHTTPSConnection object at 0x000000000391CDA0>, 'Connection to 10.1
.0.11 timed out. (connect timeout=15)')': /simple/imutils/
Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connec
tion broken by 'ConnectTimeoutError(<pip._vendor.requests.packages.urllib3.conne
ction.VerifiedHTTPSConnection object at 0x0000000003912EB8>, 'Connection to 10.1
.0.11 timed out. (connect timeout=15)')': /simple/imutils/
Could not find a version that satisfies the requirement imutils (from versions
: )
No matching distribution found for imutils

Example of using range-detector

Hello Adrian,

Thanks for your library.
Could you please provide the example how to use range detector?
Suppose I have the image with the specific object I want to be detected. Should I make the screenshot with the only that object present in the image?
How exactly can I run it? I have tried to import it and find function range_detector() but it doesn't exist.
I have tried to run it with the command ./range-detector -f HSV -i /path/to/image/image.jpg but then I got error

computer-vision $ ./imutils/bin/range-detector -h
Traceback (most recent call last):
  File "./imutils/bin/range-detector", line 10, in <module>
    import cv2
ImportError: No module named cv2

I have cv2 libraby and can use it via jupyter notebook as well.
Could you please help me please with this issue?

Illegal instruction

Hello,

I have a python3 script on my computer that I can run with python3 motion_detection.py and that works, I tried to use it on my Raspberry and something fails with message Illegal instruction. The line that throws this error is: frame = imutils.resize(frame, width=500)

Here is the minimalist sample of code:

import imutils
import cv2
frame = cv2.imread('test.jpg')
frame = imutils.resize(frame, width=500)

I'm sure that frame is not None because I tried to save it and it worked.
I'm a bit confused because there is no more explaination that Illegal instruction
I checked the version of imutils that is the same on my computer that on the Raspberry (0.4.6)

Can someone help me please ?

`perspective.order_points()` doesn't work as expected

I read your "Measuring Size of an object using OpenCV" article, and while I was running it I kept getting a weird answer for one of the objects i'm measuring. The points for the bounding box are:

[[ 2130.,  1773.],
 [ 2161.,  1552.],
 [ 2153.,  1551.],
 [ 2138.,  1774.]]

and I get this answer reliably from perspective.order_points(). I've even run a loop randomizing the order of the points and it keeps giving me this back. While that might be good, this is not top-left, top-right, bottom-right, bottom-left order. This is bottom-left, top-right, top-left, bottom-right order.

I noticed that your previous post was about fixing a bug that put the points out of order, but not only did I double check that I have the latest imutils:

➜  2D-image-meas pip show imutils

---
Metadata-Version: 1.1
Name: imutils
Version: 0.3.6

but I also copy-pasted the code from that post and it gave me the same answer.

Thank you for your time, any help is appreciated!!

AttributeError: module 'imutils.face_utils' has no attribute 'FACIAL_LANDMARKS_IDXS'

imutils module is installed in my pc but still i am getting this error.I have python 3.6.4 version.
Please if anyone find the solution for this ,please let me know.
Thanks in advance!!

python3 detect_blinks.py --shape-predictor shape_predictor_68_face_landmarks.dat
[INFO] loading facial landmark predictor...
Traceback (most recent call last):
File "detect_blinks.py", line 59, in
(lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS["left_eye"]
AttributeError: module 'imutils.face_utils' has no attribute 'FACIAL_LANDMARKS_IDXS'

ImportError: No module named imutils

Hello,
I installed imutils in Ubuntu 16.04 using the next command:

sudo pip apt-get install imutils

I ran "pip list" and show me that imutils (0.4.3) is already installed, but when I tried to use it in a python script:

import imutils

show me the next error:

Traceback (most recent call last):
File "/home/epic/Documentos/python test/OpenCV/curso/test2.py", line 3, in
import imutils
ImportError: No module named imutils

any idea what is wrong?

SALUDOS!!!!!!!!!!

imutils import error in pythin 3.6

I have installed imutils using pip3 install imutils with python 3 version as 3.6.3 .But when I try to imprt it it gives me ImportError for imutils, althought the requirement is already satisifed in /usr/lib/python3.6/site-packages.

instapy - cannot import name 'log_uncertain_unfollowed_pool'

C:\Users\User\Downloads\InstaPy-master>python quickstart.py
Traceback (most recent call last):
File "quickstart.py", line 1, in
from instapy import InstaPy
File "C:\Users\User\Downloads\InstaPy-master\instapy_init_.py", line 2, in
from .instapy import InstaPy
File "C:\Users\User\Downloads\InstaPy-master\instapy\instapy.py", line 35, in
from .unfollow_util import get_given_user_followers
File "C:\Users\User\Downloads\InstaPy-master\instapy\unfollow_util.py", line 12, in
from .print_log_writer import log_uncertain_unfollowed_pool
ImportError: cannot import name 'log_uncertain_unfollowed_pool' from 'instapy.print_log_writer' (C:\Users\User\Downloads\InstaPy-master\instapy\print_log_writer.py)

PEP8 checking

Hello,

Your code need some cleanup to respect PEP8.
I suggest to use flake8 for lint.

flake8 --ignore E501 imutils demos

This can be run on CI server (Travis...) just after running unit tests

Kind regards

'NoneType' object has no attribute 'shape'

Hello;
I‘m running the real_time_object_detection program,and the problem is :D:\python3.5.2\Model\object-detection-deep-learning>python real_time_object_detection.py --prototxt=MobileNetSSD_deploy.prototxt.txt --model=MobileNetSSD_deploy.caffemodel
[INFO] loading model...
[INFO] starting video stream...
Traceback (most recent call last):
File "real_time_object_detection.py", line 44, in
frame = imutils.resize(frame, width=400)
File "C:\Anaconda3\lib\site-packages\imutils\convenience.py", line 69, in resize
(h, w) = image.shape[:2]
AttributeError: 'NoneType' object has no attribute 'shape'

the code is:

import the necessary packages

from imutils.video import VideoStream
from imutils.video import FPS
import numpy as np
import argparse
import imutils
import time
import cv2

construct the argument parse and parse the arguments

ap = argparse.ArgumentParser()
ap.add_argument("-p", "--prototxt", required=True,
help="path to Caffe'deploy'prototxt file")
ap.add_argument("-m", "--model", required=True,
help="path to Caffe pre-trained model")
ap.add_argument("-c", "--confidence", type=float, default=0.2,
help="minimum probability to filter weak detections")
args = vars(ap.parse_args())

initialize the list of class labels MobileNet SSD was trained to

detect, then generate a set of bounding box colors for each class

CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
"bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
"dog", "horse", "motorbike", "person", "pottedplant", "sheep",
"sofa", "train", "tvmonitor"]
COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))

load our serialized model from disk

print("[INFO] loading model...")
net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])

initialize the video stream, allow the cammera sensor to warmup,

and initialize the FPS counter

print("[INFO] starting video stream...")
vs = VideoStream(src=1).start()
time.sleep(2.0)
fps = FPS().start()

loop over the frames from the video stream

while True:
# grab the frame from the threaded video stream and resize it
# to have a maximum width of 400 pixels
frame = vs.read()
frame = imutils.resize(frame, width=400)

# grab the frame dimensions and convert it to a blob
(h, w) = frame.shape[:2]
blob = cv2.dnn.blobFromImage(frame, 0.007843, (300, 300), 127.5)

# pass the blob through the network and obtain the detections and
# predictions
net.setInput(blob)
detections = net.forward()

loop over the detections

for i in np.arange(0, detections.shape[2]):
	# extract the confidence (i.e., probability) associated with
	# the prediction
	confidence = detections[0, 0, i, 2]

	# filter out weak detections by ensuring the `confidence` is
	# greater than the minimum confidence
	if confidence > args["confidence"]:
		# extract the index of the class label from the
		# `detections`, then compute the (x, y)-coordinates of
		# the bounding box for the object
		idx = int(detections[0, 0, i, 1])
		box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
		(startX, startY, endX, endY) = box.astype("int")

		# draw the prediction on the frame
		label = "{}: {:.2f}%".format(CLASSES[idx],
			confidence * 100)
		cv2.rectangle(frame, (startX, startY), (endX, endY),
			COLORS[idx], 2)
		y = startY - 15 if startY - 15 > 15 else startY + 15
		cv2.putText(frame, label, (startX, y),
			cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)

show the output frame

cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF

# if the `q` key was pressed, break from the loop
if key == ord("q"):
	break

# update the FPS counter
fps.update()

stop the timer and display FPS information

fps.stop()
print("[INFO] elapsed time: {:.2f}".format(fps.elapsed()))
print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))

do a bit of cleanup

cv2.destroyAllWindows()
vs.stop()

may be the problem is it didn't active the camera when I was running “vs = VideoStream(src=1).start()”?
appreciated for helping me,Thank you.

No module named 'imutils' after pip install

I just followed this guide here to install OpenCV: http://www.pyimagesearch.com/2016/12/19/install-opencv-3-on-macos-with-homebrew-the-easy-way/

And then followed this guide here: http://www.pyimagesearch.com/2016/02/08/opencv-shape-detection/

I've pip-installed imutils, but keep getting the error below.

sudo pip install imutils
...
Collecting imutils
  Downloading imutils-0.4.2.tar.gz
Installing collected packages: imutils
  Running setup.py install for imutils ... done
Successfully installed imutils-0.4.2
hdmih0445m:shape-detection bstadin$ 

The install seems to be ok, trying to reinstall imutils gives:

Requirement already satisfied: imutils in /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages

Running a script importing imutils:

python3 detect_shapes.py --image /Users/bstadin/Downloads/image.png
...
Traceback (most recent call last):
  File "detect_shapes.py", line 7, in <module>
    import imutils
ModuleNotFoundError: No module named 'imutils'

FileVideoStream Problem: FATAL: exception not rethrown Aborted (core dumped)

Code:

fvs = FileVideoStream("./1_2017-03-17_08-38-27.mp4")
fvs.start()
num = 0
while fvs.more():
frame = fvs.read()
if frame is None:
print("Break!")
break
print(num)
num = num +1
print("finished!")
fvs.stop()

First, It wouldn't print the number, that means fvs.more() doesn't work.
And it would raise a ERROR at last.
Notice, the path of video is on the way.
How can I deal with my problem?

pip installed version of order_points give wrong answer

I recently installed via pip and then spent the next 4 days trying to work out why my 4 point perspective transform was failing.

The version of the order_points function was returning the wrong sequence, when I replace the shipped version with the version on this page the transform works as expected.

Example code to show the error can be found here:

http://www.hardill.me.uk/sample.tgz

$ pip show imutils

Name: imutils
Version: 0.3.6
Location: /usr/local/lib/python2.7/dist-packages
Requires:

AttributeError: 'NoneType' object has no attribute 'shape'Human semantic parsing for re-identification have a problem..

Traceback (most recent call last):
File "/home/lvv/anaconda2/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/home/lvv/anaconda2/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/lvv/anaconda2/lib/python2.7/site-packages/chainer/iterators/multiprocess_iterator.py", line 336, in _run
alive = self._task()
File "/home/lvv/anaconda2/lib/python2.7/site-packages/chainer/iterators/multiprocess_iterator.py", line 355, in _task
data_all = future.get(_response_time)
File "/home/lvv/anaconda2/lib/python2.7/multiprocessing/pool.py", line 572, in get
raise self._value
AttributeError: 'NoneType' object has no attribute 'shape'

corners_to_keypoints fails when no corners detected

Overview

The corners_to_keypoints utility does not perform any checks on the input to ensure it is an iterable as expected. This can cause error if using a GFTT keypoint detector on an image that doesn't have any keypoints found (ie corners_to_keypoints(None)).

(I ran into the issue with all black images from a VideoCapture while the camera was starting up)

Example to reproduce error

import cv2
import numpy as np
import imutils.feature.factories as kp_factory

# create blank all black 'image'
image = np.zeros(16, dtype='uint8').reshape(4, 4)

# init gftt keypoint detector using imutils factory
kp_detector = kp_factory.FeatureDetector_create('GFTT')

# detect keypoints in blank image (same defaults as `FeatureDetector_create('GFTT')`)
# result assigned to cv2_kps is `None`
cv2_kps = cv2.goodFeaturesToTrack(image, 0, 0.01, 1)  

# attempt keypoint detection with imutils (causes error below)
imutils_kps = kp_detector.detect(image)

Resulting error

Traceback (most recent call last):
   File "test_kp_none.py", line 12, in <module>
      imutils_kps = kp_detector.detect(image)
   File ".../imutils/imutils/feature/gftt.py", line 21, in detect
      return corners_to_keypoints(cnrs)
   File ".../imutils/imutils/feature/helpers.py", line 6, in corners_to_keypoints
      return [cv2.KeyPoint(kp[0][0], kp[0][1], 1) for kp in corners]
TypeError: 'NoneType' object is not iterable

Proposed fix

A simple if else to return None [] if the input to corners_to_keypoints is None. This fixes the error and seems to mirror the cv2 behavior is consistent with the other imutils kp detectors when no keypoints are found. I've only tested with 'GFTT' created by the imutils factory because from it looks like thats the only place corners_to_keypoints is used.

def corners_to_keypoints(corners):
    """function to take the corners from cv2.GoodFeaturesToTrack and return cv2.KeyPoints"""
    if corners is None:
        keypoints = []
    else:
        keypoints = [cv2.KeyPoint(kp[0][0], kp[0][1], 1) for kp in corners]

    return keypoints

Edit: converted output from None to [] to be consistent with other keypoint detectors.

import imutils error in Debian

Hi Jrose,

I am trying to import imutils in Debian distro running on BeagleBone Black. This is what im getting when i import it in the Python Interpreter;
root@beaglebone:~# python
Python 2.7.3 (default, Mar 14 2014, 17:55:54)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.

import imutils
Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python2.7/dist-packages/imutils/init.py", line 5, in
from .convenience import translate
File "/usr/local/lib/python2.7/dist-packages/imutils/convenience.py", line 108, in
def url_to_image(url, readFlag=cv2.IMREAD_COLOR):
AttributeError: 'module' object has no attribute 'IMREAD_COLOR'

How can i rectify the problem?

problem with filename with spaces

Hi Adrian,

It seems like cv2.imread() doesn't like the backslash prefix for space in a file name. It turns None in this case. I understand there must be other cases the backslash is required. However should we have a better way to handle this?

My cv2 is 3.2.0, python is 3.6.5 on Ubuntu 18.04. If the filename contains a space, cv2.imread(imutile.paths.list_images(filename_with_space)) returns None. It can be fixed if I modify https://github.com/jrosebr1/imutils/blob/master/imutils/paths.py line 24 as below (remove the .replace(" ", "\ ") part).

imagePath = os.path.join(rootDir, filename)

Thanks,
-yi

paths.py - replacing space with slash+space

Hi!

First of all, thanks for the library. Very useful!
Second, I wanted to ask you why do you replace space with slash+space in paths.py? Is this a bug or something you've done on purpose?

imagePath = os.path.join(rootDir, filename).replace(" ", "\\ ")

PS: I'm using Windows and Python3.

ImportError: No module named imutils

User-MacBook-Pro:~ user$ sudo pip install imutils

Collecting imutils
Installing collected packages: imutils
Successfully installed imutils-0.5.1
User-MacBook-Pro:~ user$ -H
-bash: -H: command not found
User-MacBook-Pro:~ user$ sudo -H pip install imutils
Requirement already satisfied: imutils in /usr/local/lib/python2.7/site-packages (0.5.1)

Installed imutils for Python2.7
and when I checked whether it is importing imutils library successfully or not then it displayed the following error message:

User-MacBook-Pro:~ user$ python
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 12:01:12)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

import imutils
Traceback (most recent call last):
File "", line 1, in
ImportError: No module named imutils

What is the problem here and how to fix it??

Unable to cast Python instance to C++ type

RuntimeError                              Traceback (most recent call last)
<ipython-input-8-407e53f9ba21> in <module>()
     65         faceOrig = imutils.resize(img[yw1:yw1 + h, xw1:xw1 + w], width=256)
     66 
---> 67         faceAligned = fa.align(img, gray, rect)
     68 
     69         path = '/home/saadi/Learningfolder/croped images/'

/home/saadi/.virtualenvs/keras-latest/local/lib/python2.7/site-packages/imutils/face_utils/facealigner.pyc in align(self, image, gray, rect)
     22         def align(self, image, gray, rect):
     23                 # convert the landmark (x, y)-coordinates to a NumPy array
---> 24                 shape = self.predictor(gray, rect)
     25                 shape = shape_to_np(shape)
     26 

RuntimeError: Unable to cast Python instance to C++ type (compile in debug mode for details)

I am trying to run this code in jupyter notebook. this is the error that I am getting.
If I run the code in simple python environment it runs perfectly. Any suggestions???

pip3 install issues

hello
I had some problem that installed library in python3.5 (windows)
I tried pip3 install imutils & pip install imutils

but my error that show blow.

Could not find a version that satisfies the requirement imultis (from versions: )
No matching distribution found for imultis

Blocking use of WebcamVideoStream.read()

Hi, first of all, thanks for this library. I'm having a lot of fun using it with opencv.

While using the WebcamVideoStream class, I came across something odd. After calculation, I found out that my video loop was displaying ~280 fps. Actually I was looping and making calculations on the same image over and over :/
screenshot from 2018-05-11 21-35-33

After some researches I found an article from you and in the comment section, people were making the same observations.

Sorry if I am misinterpreting your implementation, but this seems more like a bug to me than a feature.
I would like to make a PR to fix this behavior or at least let people choose if they want to wait for the frame or if they prefer requesting the same image over and over (which is a bit odd to me).

Have a nice day, cheers !

After pip install, ImportError: No module named imutils

It's probably my own fault, but maybe somebody can help me.

As the description says:
"Provided you already have NumPy, SciPy, Matplotlib, and OpenCV already installed, the imutils package is completely pip-installable"
I pip installed imutils.
However, when I try to import it, python says:
ImportError: No module named imutils

This is my console:
hardware@debian:~$ python
Python 2.7.9 (default, Jun 29 2016, 13:08:31)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.

import imutils
Traceback (most recent call last):
File "", line 1, in
ImportError: No module named imutils

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.