You know what’s a really good feeling?
Contributing to the open source community.
PyPI, the Python Package Index repository is a wonderful thing. It makes downloading, installing, and managing Python libraries and packages a breeze.
And with all that said, I have pushed my own personal imutils package online. I use this package nearly every single day when working on computer vision and image processing problems.
This package includes a series of OpenCV + convenience functions that perform basics tasks such as translation, rotation, resizing, and skeletonization.
A diverse image dataset is beneficial for testing the convenience functions in the imutils package. It allows users to explore how these functions can simplify common tasks in image processing.
Roboflow has free tools for each stage of the computer vision pipeline that will streamline your workflows and supercharge your productivity.
Sign up or Log in to your Roboflow account to access state of the art dataset libaries and revolutionize your computer vision pipeline.
You can start by choosing your own datasets or using our PyimageSearch’s assorted library of useful datasets.
Bring data in any of 40+ formats to Roboflow, train using any state-of-the-art model architectures, deploy across multiple platforms (API, NVIDIA, browser, iOS, etc), and connect to applications or 3rd party tools.
In the future we will (probably, depending on feedback in the comments section) be performing a detailed code review of each of the functions in the imutils
package, but for the time being, take a look at the rest of this blog post to see the functionality included in imutils
, then be sure to install it on your own system!
Installing
This package assumes that you already have NumPy and OpenCV installed (along with matplotlib, if you intend on using the opencv2matplotlib
function).
To install the the imutils
library, just issue the following command:
$ pip install imutils
My imutils package: A series of OpenCV convenience functions
Let’s go ahead and take a look at what we can do with the imutils
package.
Translation
Translation is the shifting of an image in either the x or y direction. To translate an image in OpenCV you need to supply the (x, y)-shift, denoted as (tx, ty) to construct the translation matrix M:
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:
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:
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:
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 explicity 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:
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:
What's next? We recommend PyImageSearch University.
86 total classes • 115+ hours of on-demand code walkthrough videos • Last updated: October 2024
★★★★★ 4.84 (128 Ratings) • 16,000+ Students Enrolled
I strongly believe that if you had the right teacher you could master computer vision and deep learning.
Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?
That’s not the case.
All you need to master computer vision and deep learning is for someone to explain things to you in simple, intuitive terms. And that’s exactly what I do. My mission is to change education and how complex Artificial Intelligence topics are taught.
If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to successfully and confidently apply computer vision to your work, research, and projects. Join me in computer vision mastery.
Inside PyImageSearch University you'll find:
- ✓ 86 courses on essential computer vision, deep learning, and OpenCV topics
- ✓ 86 Certificates of Completion
- ✓ 115+ hours of on-demand video
- ✓ Brand new courses released regularly, ensuring you can keep up with state-of-the-art techniques
- ✓ Pre-configured Jupyter Notebooks in Google Colab
- ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
- ✓ Access to centralized code repos for all 540+ tutorials on PyImageSearch
- ✓ Easy one-click downloads for code, datasets, pre-trained models, etc.
- ✓ Access on mobile, laptop, desktop, etc.
Summary
So there you have it — the imutils package!
I hope you install it and give it a try. It will definitely make performing simple image processing tasks with OpenCV and Python substantially easier (and with less code).
In the coming weeks we’ll perform a code review of each of the functions and discuss what is going on under the hood.
Until then!
Downloads:
Grab the imutils package from GitHub.
Join the PyImageSearch Newsletter and Grab My FREE 17-page Resource Guide PDF
Enter your email address below to join the PyImageSearch Newsletter and download my FREE 17-page Resource Guide PDF on Computer Vision, OpenCV, and Deep Learning.
David Tran
Hi Adrian,
I’m trying to get your imutils package for a project that I’m working on, but from importing imutils I get the error: ‘module’ object has no attribute ‘IMREAD_COLOR’. The error seems to come from the url to image function’s second parameter, readFlag=cv2.IMREAD_COLOR.
I’m working on python 2.7. Could it be a problem with OpenCV? I have 2.4.10 installed.
Thanks a bunch!
Adrian Rosebrock
Hey David, that does indeed sound like an OpenCV problem, but as far as I know the
cv2.IMREAD_COLOR
is part of OpenCV 2.4.5+. Can you try manually editing the code to setreadFlag=1
and see if that resolves the issue?UPDATE:
I just tried on OpenCV 2.4.10.1. The
cv2.IMREAD_COLOR
flag is definitely present:>>> import cv2
>>> cv2.__version__
'2.4.10.1'
>>> cv2.IMREAD_COLOR
1L
Ashwini Gat
sir how to install imutils package in window 7 32bit without pip installer
Adrian Rosebrock
You could always clone the repository from GitHub and manually copy the
imutils
directory into thesite-packages
directory of your Python installation, but it’s much easier to let pip do it for you.HaliseT
Hi,
I’m new to python and computer vision. I’m using ubuntu 14.04 OS and when I type the command pip install imutils i get the following error:
could not create
'/usr/local/lib/python2.7/dist-packages/imutils': Permission denied
is there another way I could install it?
Thanks
Adrian Rosebrock
It sounds like you need to let
sudo
install it for you:$ sudo pip install imutils
Shelly
Looks like a useful package! It seems like conda can’t find it, though. Any plans to make that happen?
Adrian Rosebrock
You should be able to let pip, the Python package manager, install it for you. I’m personally not a conda user and I don’t have any plans to work with them.
ST
Hi Shelly,
You can uninstall system pip by ‘pip uninstall pip’. Then install pip through conda ‘conda install -c anaconda pip=9.0.1 ‘. Check whether your current pip location is from conda by typing ‘pip -V’. This should show something like ‘pip 9.0.1 from C:\Continuum\Anaconda3\lib\site-packages (python 3.5)’. Then install imutils by ‘pip install imutils’. This will install imutils to your conda environment.
ST
Cristhian
Hello
I have solved the previous problem opencv
now my question I get an error when using imutils
please help me
====>
Adrian Rosebrock
You need to install the
imutils
package:$ pip install imutils
Antony Smith
I can import the imutils package outside of my (cv) environment, but within it where I have opencv installed it says “ImportError: No module named imutils”.
But then within the (cv) I try:
sudo -H pip3 install imutils –upgrade
and it says “already satisfied”?
This is kind of the reason why I always avoid the virtual env thing.
It throws irritating errors like this.
Adrian Rosebrock
Hey Anthony — you may find virtual environments irritating at first, but they are a best practice. Secondly, a little bit of education goes a long way. By supplying the “sudo” command you are instructing your shell to install imutils into your system install of Python, NOT your Python virtual environment!
Instead, you can install imutils into the “cv” Python virtual environment via:
Again, a little bit of education goes a long way so I suggest you read up on Python virtual environments.
Antony Smith
figured out what I was doing wrong in the virtualenv. Need to avoid buzz commands like “sudo -H”.
Just a direct:
“pip3 install –upgrade imutils” has installed it to the env.
Cristina
Hello, I need to do the same thing, but in C++.
Do you know if there is something like imutils for c++ ?
Thanks
Adrian Rosebrock
I personally don’t do much work in C++, at this point I do mainly Python, so I’m not too privy with the latest C++ libraries. If I run across anything that looks interesting, I’ll be sure to post it here.
Francisco
Do you know how can I install imutils via LiClipse?, i dont wanna mess with prompt.
Is matplotlib necessary to make the ball tracking, i mean the contour.
Regards
Adrian Rosebrock
I don’t personally use LiClipse, but I would suggest becoming familiar with the prompt. Nearly all examples on the PyImageSearch blog require using the command line. It’s best to start getting used to it and working with it now.
As for matplotlib, no, it is not required for tracking objects in images.
Asha
I installed imutils-0.3.6 using pip and also upgraded.It gives following error while importing..
>>> import imutils
>>> from imutils import paths
Traceback (most recent call last):
File “”, line 1, in
from imutils import paths
ImportError: cannot import name paths
>>> from imutils.object_detection import non_max_suppression
Traceback (most recent call last):
File “”, line 1, in
from imutils.object_detection import non_max_suppression
ImportError: No module named object_detection
please help..
Adrian Rosebrock
It sounds like you’re using an old version of imutils. Make sure you have updated to the latest version:
pip install --upgrade imutils
San
Hi Adrian,
I installed imutils using pip. But I can’t import it when inside virtual env, but can import when not inside virtual env. What might be the solution?
Adrian Rosebrock
Make sure you use the
workon
command to access your Python virtual environment first and then installimutils
into the virtual environment:See0507
My problem is similar. I installed imutils with pip, inside the virtual env! But I cant import it although I can find it with the file manager. I´m confused.
Adrian Rosebrock
It sounds like you are not in your virtual environment when importing
imutils
:Again, make sure you are in the correct Python virtual environment before importing the library.
See0507
It is possible to import in the console, but when I start my script out of python with F5 it says “no module named imutils” in the python shell.
Opening the file by console is not possible either:
python: cant open file “motion_capt.py” : [Errno 2] No such file or directory.
Have I to save the file at a specific place?
Adrian Rosebrock
It sounds like you are using some sort of IDE for writing your code. If you’re using Python virtual environments, then you likely need to set the correct Python interpreter for your IDE.
See0507
I´m using the preinstalled python 3 IDE on Raspbian, could you give a short tutorial how to “set the correct Python interpreter for my IDE”. I´m sorry, but this whole Linux/raspi/etc thing is relatively new to me.
Adrian Rosebrock
Instead of using the pre-installed Python IDLE, execute the script via the command line from within your
cv
virtual environment. You can learn more about virtual environments in this post.Havan
Hey Adrian , when i am trying to install imutils using pip inside virtual environment it give error that:
Could not find a version that satisfies the system requirements imutios.
What to do???
Adrian Rosebrock
There is a typo in your command. You are tying “imutios”, but the library is actually named “imutils”:
$ pip install imutils
Mrjosh
I’m having the same issue. I have checked the spelling, same error. Asn’t suggestions? The code I’m using is the motion detection tutorial article 2
Adrian Rosebrock
What operating system are you using? Are you using Anaconda or standard Python virtual environments?
Daniella Solomon
There is option to to resize image both width and height (not just one of them)?
p.s it will be lovely to get some notification by mail or something else when you/ your team response to comment (for me it’s difficult to track all my comments – it’a s lot, lol..)
Adrian Rosebrock
If you want to resize on just one dimension and ignore the aspect ratio you should simply call
cv2.resize
directly. An example can be found in in this blog post. You’ll also find a more detailed explanation inside Practical Python and OpenCV.Rolf
Hello Adrian,
after installing opencv 3.1.0 and Python 3.4.2 .
(A BIG Thank you for the fantastic help provided by your work…)
I get the following message when launching skindetector.py
Traceback (most recent call last):
…
(h, w) = image.shape[:2]
AttributeError: ‘NoneType’ object has no attribute ‘shape’
Is it a message linked with Python version ? and how should I patch it ?
Thank you in advance
Adrian Rosebrock
This sounds like an issue with (1) loading an image from disk or (2) accessing a video stream. I explain how to diagnose and resolve NoneType errors in this blog post.
Y CHETHAN REDDY
Hello Rolf
Were you able to solve this problem . I too have the same issue ,could you please help me out . Thanks in advance
Yugank
I have been trying to install this package but whenever I do it shows error.
I type:- pip install imutils
Error Received:- SyntaxError: invalid syntax
Please help me with this.
Adrian Rosebrock
It sounds like you are inside the Python shell. You shouldn’t be. Don’t start the Python program. Simply open up a terminal and type:
$ pip install imutils
Kalyani
I am still getting the same error even after typing the command with $. Also I wrote it on terminal and I am not inside the Python shell. Will you please help
Adrian Rosebrock
You do not type the “$”. The dollar sign indicates the shell. You need to execute “pip install imutils” from your shell.
Svein
Awesome, just got it to work with opencv 3.2, cuda 8.0 and latest dlib tools.. was considering creating a library like this myself !
Adrian Rosebrock
Congrats, nice job Svein!
Shazam
I am trying to use your Color Kmeans code with Imutils package but when I run the program, it tells me: “AttributeError: module ‘imutils’ has no attribute ‘centroid_histogram’ ”
Is this attribute no longer part of imutils?
Adrian Rosebrock
Make sure you use the “Downloads” section of the blog post to download the source code to the blog post which includes all necessary code for the project. That will resolve the error.
shaquiel oneal
Hey adrian,
How can i use the opencv’s videocapture.get function using imutils’s FileVideoStream?
Adrian Rosebrock
Right now there isn’t a way to do that. You would need to modify the
FileVideoStream
class and either pass in a pre-instantiatedcv2.VideoCapture
object or (better yet) simply create your own version ofFileVideoStream
that performs the logic you want it to based on the.get
call.shaquiel oneal
Hey,
thanks for your quick reply.
Python isn’t exactly my mother’s,
but right now i can attend to FileVideoStream(videoPath).start().get in a static way,
is it a bad practice?
Adrian Rosebrock
No, that’s perfectly fine and will work.
raspi
Im using a raspberry pi 2 and have installed imutils into the virtual environment using pip , however i am not able to import imutils in python 2.7. python says no module named imutils.
Adrian Rosebrock
Make sure you are in your virtual environment via
workon your_env_name
before runningpip install imutils
and then trying to import the library.Rithika Shyam Chari
Hi..Thank you for the great post. I am running Python 3.5 and Python 2.7 on a 64bit env (Windows 10). I am trying to get OpenCV to work. I tried different versions but I am running into DLL load failed: %1 is not a valid Win32 application errors. I tried to run opencv (latest version) but there was some error in the convenience.py.
Any heads up on the compatible versions is much appreciated. Thanks in advance.
Adrian Rosebrock
Hi Rithika — thanks for the comment; however, I do not support Windows here on the PyImageSearch blog. I only support Unix-based environments such as macOS and Linux. If at all possible, please use either macOS or Linux when following the tutorials here on PyImageSearch.
For what it’s worth, I offer a pre-configured Ubuntu VirtualBox virtual machine with OpenCV pre-installed as part of the Quickstart Bundle and Hardcopy Bundle of my book, Practical Python and OpenCV. This is by far the fastest way to get up and running with OpenCV. The VM will also run on Windows.
Robert
I’m using rasipian stretch and I have successfully installed imutils as when I type pip freeze it appears, however I can’t run any code with it because as soon as I put it in a script it say no module can be found
Adrian Rosebrock
How are you executing your Python script? Via command line? Are you using Python virtual environments? If you used Python virtual environments make sure you installed “imutils” into it AND you are inside the Python virtual environment when you execute the script.
Robert
yes I my code is:
source ~/.profile
workon cv
cd ~/Python_Prorgrams
sudo python script.py
By doing this it says that imutils cannont be found however when I run in a python shell
(Code for this:
source ~/.profile
workon cv
cd ~/Python_Prorgrams
sudo python
import imutils
)
it works fine with no error occurring
Adrian Rosebrock
Hi Robert — Is there a reason you’re running Python with the super user (sudo)? Check out this thread on SOF.
Avinash
Adrian Help me to install ” fom pyimagesearch.facedetector import FaceDetector ”
I don’t know how to install that pyimagesearch facedetector module
Adrian Rosebrock
Please use the “Downloads” form to download the source code and “pyimagesearch” module for the blog post you are referring to. The “Downloads” section will contain the module and code you are looking for.
Manik
Sir please suggest a good book for feature extraction of images using image transforms for classification…….
Adrian Rosebrock
Hi Manik,
The PyImageSearch Gurus course includes over 30+ lessons on image classification via feature extraction. I suggest you start there.
Antony
Adrian, my man, you’re an absolute legend!
Adrian Rosebrock
Thank you for the kind words, Antony 🙂
gaeta
how do i resize an image up to 320×240 image
cap1 = imutils.resize(frame, width=320, height= 240)
doesn’t work
Adrian Rosebrock
Just call
cv2.resize
directly:image cv2.resize(image, (320, 240))
The imutils function will preserve the aspect ratio, hence why it’s not behaving like you would expect it to.
Aakash
Hey, I’m unable to import build_montages.
from imutils import build_montages
I have updated my imutils
Adrian Rosebrock
It sounds like either:
1. You did not install imutils
2. The ‘pip install imutils’ command exited with an error
3. You installed imutils into a separate Python version (perhaps a Python virtual environment) than the one you are using
Double-check the three above.
Aneesh Bhat
Wow! These functions helped me a lot on my project!!! Thanks a bunch!
Alex Novic
Adrian, hi! Glad to write you directly. (Cause you’re a legend for many of us :)) I have a strange behavior of the WebcamVideostreamCapture function. I am trying to show the stereo-image from two stereo-webcams on the RPi3’s 5″ TFT display. When I am using one camera the FPS (measured by your FPS-demo prog) is approx 56. But two cams, i.e. two objects generated by WebcamVideostreamCapture, dramatically decreases the FPS. Videos freezes for half of second and more. As soon as I am just adding a second object, FPS falls to the ground. I feel, something is in the RPi’s settings. I mean threading. Please help with this question.
Adrian Rosebrock
Keep in mind that the code is measuring the FPS throughput rate of the pipeline, not the actual FPS of the camera itself. I would suggest using the
multiprocessing
package instead ofthreading
— that may give you a faster throughput rate.Rohan Sathasivam
Hi Ardian, I tried to use the function ”visualize_facial_landmarks’ from imutils library. However, it throws me an error: module ‘imutils’ has no attribute ‘visualize_facial_landmarks’. Could you please advise what needs to be done to trigger this function.
Rohan Sathasivam
I got it. Than you!. Your logical explanations are crystal clear. Thanks again
Adrian Rosebrock
Congrats on resolving the issue, Rohan!
Prince Sanjivy
Hey, I just want to know is there an abbreviation for “imutils” ?
Adrian Rosebrock
Are you asking what the abbreviation for “imutils” is? If so, it’s short for “image utilities”.
Adrian
Hello Adrian!, can you tell me or write in this post about Object Detection in imutils?
what is the best way to use?
Thanks! i been follow 4 or 5 years!
i like very much your work.
Adrian Rosebrock
I actually cover object detection in detail inside the PyImageSearch Gurus course as well as Deep Learning for Computer Vision with Python. I would suggest starting there.
Monish
Hello Adrian,
Could you please tell me as to what license ‘ imutils ‘ comes under?
Adrian Rosebrock
The “imutils” library is MIT. I would appreciate credit and a link back to the PyImageSearch blog if you ever use it though!
Jakan
hi Adrian
I’m getting lots of information from this site.
Is there a way to know the arguments and functions of the imutils library(package)?
Adrian Rosebrock
The library is open source. You can find it here.
Ishit Gandhi
Hi Adrian,
I am using imutils’s videostream to read the stream from webcam, how I can get video stream metadata?
cv2.CAP_PROP_FPS
cv2.CAP_PROP_FRAME_WIDTH
cv2.CAP_PROP_FRAME_HEIGHT
none of these properties works with it.
should we define function get_props() in webcamvideostream.py and initialize different metadata properties and use it?
Adrian Rosebrock
This PR, which will soon be merged into imutils, enables you to set capture properties.
Harshit
Adrian Sir, I am trying to understand the FPS module in imutils,Can you provide the documentation of it.
I want to run my code on different machines and set the fps of those machines to a fix value for the duration of my program running.
Adrian Rosebrock
Make sure you use the “Search” functionality on the PyImageSearch site. I’ve covered it before.
Steve SIlvi
Hi Adrian,
I’m using imutils in your Python script to stream Pi camera video to a web browser. The script runs properly, but for the life of me I cannot figure out how to rotate the video stream. Adding vs.flip = True does not work; neither does cv2.flip = True work. No Python errors are thrown, but neither command flips the video output. I’ve searched the web but most of the info out there pertains to flipping a specific image, but I don’t know if a video stream can be defined as an image. Can you help. Thanks.
Adrian Rosebrock
You can flip the frame via:
image = cv2.flip(image, 1)