1. Imutils Функция
Imutils — это пакет, основанный на OpenCV для достижения более простых для вызова интерфейса OpenCV, который может легко реализовать серию операций, таких как перевод изображения, вращение, масштабирование и скелет.
Перед установкой вы должны подтвердить, что NUMPY, SCIPY, MATPLOTLIB и OPENCV установлены.
2. Как использовать imutils
2.1 Перевод изображения
Перевод изображений также предоставляется в OpenCV, сначала рассчитайте матрицу перевода, а затем используйте аффинное преобразование для перевода, а изображение можно перевести непосредственно в imutils.
- IMG: изображение для перемещения
- X: количество пикселей, движущихся в направлении оси X
- Y: количество пикселей, движущихся в направлении оси Y
2.2 Изображение Zoom.
Масштабирование картинок следует принимать, чтобы сохранить соотношение ширины в OpenCV. И автоматически поддерживать соотношение сторон исходного изображения в imutils, только указываю на вес и высоту ширины.
На рисунке ниже является результатом масштабирования изображения:

2.3 Вращение изображения
При вращении в OpenCV является аффинная преобразование, метод вращения изображения здесь imutils.rotate() С 2 параметрами первая — это данные изображения, второй — угол вращения, вращение находится в направлении против часовой стрелки. в то же время imutils Еще один аналогичный подход также предоставляется. rotate_round() Он вращается в зависимости от по часовой стрелке.
Результаты приведены ниже:

2.4 экстракции скелета
Экстракция скелета относится к процессу создания топологического скелета на картинке. Способ, предоставляемый IMUTILS, является скелетным (), и второй параметр является структурирующим элементом, который эквивалентен размеру частиц, а также меньшее время, которое вам нужно обрабатывать.
Эффект выглядит следующим образом:

2.5 отображение MATPLOTLIB
В привязке Python Python Openc изображение представлено как Numpy Array в порядке BGR. Использовать cv2.imshow Функция очень хорошая. Однако, если вы планируете использовать MatPlotlib, plt.imshow Функция предполагает, что изображение расположено в порядке RGB. передача cv2.cvtColor Решите эту проблему, вы также можете использовать opencv2matplotlib Удобные функции.
2.5 Обнаружение версии OpenCV
После того, как OPENCV 4 выпущен, как главная версия обновления, проблема обратной совместимости особенно заметна. При использовании OpenCV, проверьте, какую версию OpenCV использует в настоящее время, а затем используйте соответствующую функцию или метод. В подражании IS_CV2 (), IS_CV3 () и IS_CV4 () Это простая версия, которая может использоваться для автоматического определения OpenCV текущей среды.
Name already in use
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
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:
Provided you already have NumPy, SciPy, Matplotlib, and OpenCV already installed, the imutils package is completely pip -installable:
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.
Let’s find all function names that contain the text contour :
The contourArea function could therefore be accessed via: cv2.contourArea
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:

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 .

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.

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.

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.

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.

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.

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.
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.

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.
See the contents of demos/perspective_transform.py

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.
See the contents of demos/sorting_contours.py

(Recursively) Listing Paths to Images
The paths sub-module of imutils includes a function to recursively find images based on a root directory.
Assuming we are in the demos directory, let’s list the contents of the ../demo_images :
About
A series of convenience functions to make basic image processing operations such as translation, rotation, resizing, skeletonization, and displaying Matplotlib images easier with OpenCV and Python.
Imutils python что это



imutils
A series of convenience functions to make basic image processing functions such as translation, rotation, resizing, skeletonization, displaying Matplotlib images, sorting contours, detecting edges, and much more easier with OpenCV and both Python 2.7 and Python 3.
Package Health Score
Keep your project healthy
Check your requirements.txt
Snyk Vulnerability Scanner
Secure Your Project
Popularity
Total Weekly Downloads (65,943)
Direct Usage Popularity
The PyPI package imutils receives a total of 65,943 downloads a week. As such, we scored imutils popularity level to be Popular.
Based on project statistics from the GitHub repository for the PyPI package imutils, we found that it has been starred 4,097 times, and that 0 other projects in the ecosystem are dependent on it.
The download numbers shown are the average weekly downloads from the last 6 weeks.
Security
Security and license risk for latest version
We found a way for you to contribute to the project! Looks like imutils is missing a security policy.
You can connect your project’s repository to Snyk to stay up to date on security alerts and receive automatic fix pull requests.
Maintenance
Commit Frequency
Further analysis of the maintenance status of imutils based on released PyPI versions cadence, the repository activity, and other data points determined that its maintenance is Inactive.
An important project maintenance signal to consider for imutils is that it hasn’t seen any new versions released to PyPI in the past 12 months, and could be considered as a discontinued project, or that which receives low attention from its maintainers.
In the past month we didn’t find any pull request activity or change in issues status has been detected for the GitHub repository.
Community
With more than 10 contributors for the imutils repository, this is possibly a sign for a growing and inviting community.
We found a way for you to contribute to the project! Looks like imutils is missing a Code of Conduct.
Embed Package Health Score Badge
Package
Not sure how to use imutils?
To help you get started, we’ve collected the most common ways that imutils is being used within popular public projects.
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:
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 :
Output:
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:

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:
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:
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:
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 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:
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:
Output:

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:
Output:

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:
Output:
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:
Output:

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:

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:

(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 :
Imutils
Converts a list of single images into a list of ‘montage’ images of specified rows and columns. A new montage image is started once rows and columns of montage image is filled. Empty space of incomplete montage images are filled with black pixels ——————————————————————————————— :param image_list: python list of input images :param image_shape: tuple, size each image will be resized to for display (width, height) :param montage_shape: tuple, shape of image montage (width, height) :return: list of montage images in numpy array format ———————————————————————————————
# load single image img = cv2.imread(‘lena.jpg’) # duplicate image 25 times num_imgs = 25 img_list = [] for i in xrange(num_imgs):
# convert image list into a montage of 256×256 images tiled in a 5×5 montage montages = make_montages_of_images(img_list, (256, 256), (5, 5)) # iterate through montages and display for montage in montages:
cv2.imshow(‘montage image’, montage) cv2.waitKey(0)
Encodigns
Object Detection
Paths
Perspective
Utility for drawing vertically & horizontally centered text with line breaks
img – Image.
text – Text string to be drawn.
font_face – Font type. One of FONT_HERSHEY_SIMPLEX, FONT_HERSHEY_PLAIN, FONT_HERSHEY_DUPLEX, FONT_HERSHEY_COMPLEX, FONT_HERSHEY_TRIPLEX, FONT_HERSHEY_COMPLEX_SMALL, FONT_HERSHEY_SCRIPT_SIMPLEX, or FONT_HERSHEY_SCRIPT_COMPLEX, where each of the font ID’s can be combined with FONT_ITALIC to get the slanted letters.
font_scale – Font scale factor that is multiplied by the font-specific base size.
color – Text color.
thickness – Thickness of the lines used to draw a text.
line_type – Line type. See the line for details.
None; image is modified in place
imutils.text. put_text ( img , text , org , font_face , font_scale , color , thickness = 1 , line_type = 8 , bottom_left_origin = False )
Utility for drawing text with line breaks
img – Image.
text – Text string to be drawn.
org – Bottom-left corner of the first line of the text string in the image.
font_face – Font type. One of FONT_HERSHEY_SIMPLEX, FONT_HERSHEY_PLAIN, FONT_HERSHEY_DUPLEX, FONT_HERSHEY_COMPLEX, FONT_HERSHEY_TRIPLEX, FONT_HERSHEY_COMPLEX_SMALL, FONT_HERSHEY_SCRIPT_SIMPLEX, or FONT_HERSHEY_SCRIPT_COMPLEX, where each of the font ID’s can be combined with FONT_ITALIC to get the slanted letters.
font_scale – Font scale factor that is multiplied by the font-specific base size.
color – Text color.
thickness – Thickness of the lines used to draw a text.
line_type – Line type. See the line for details.
bottom_left_origin – When true, the image data origin is at the bottom-left corner. Otherwise, it is at the top-left corner.