Skip to main content

Simple helper package for opencv-python

Code style: black

cvhelper is a simpler wrapper for the opencv-python package. As mentioned package only gives access to OpenCV functions, in a C++ style, it can be tedious to write. There is also no support for the OpenCV classes like Rect, Point etc. cvhelper attempts to fix that.

The package is at an early state, and contributions are welcome! The contents of the package have been a demand-and-supply model, where functionality is added as new tedious things in opencv-python are found. Do not hesitate to file an issue, requesting new functionality or enhancement proposals!

Installation

Installation is by the python package manager, pip.

pip install cvhelper

This also installs the dependencies opencv-python, opencv-contrib-python and numpy, if not already present.

Examples

Reading videos

This code speaks for itself.

Vanilla OpenCV:

import cv2 as cv
video = cv.VideoCapture("path/to/file")
if not video.isOpened():
    raise ValueError("Could not open video")

while True:
    ok, frame = video.read()
    if not ok:
        break
    cv.imshow("Frame", frame)
    if cv.waitKey(0) & 0xFF == ord('q'):
        break 
video.release()

cvhelper:

import cv2 as cv
import cvhelper as cvh
with cvh.load_video("path/to/file") as video:
   for frame in cvh.read_frames(video, start, stop, step):
       cv.imshow("Frame", frame)
       if cvh.wait_key(0) == ord('q'):
            break 

Rotate A Color Wheel

Say we have the following color wheel image, which we want to rotate.

alt text

We of course want to rotate it at it's center, which is not in the center of the image. A possible solution using OpenCV would be

import cv2 as cv
import random

img = cv.imread("resources/color_wheel_invert.png")
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
_, otsu = cv.threshold(gray, 250, 255, cv.THRESH_BINARY_INV)
_, contours, _ = cv.findContours(otsu, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
contour = contours[0]
rect = cv.boundingRect(contour)  # Gives a tuple (x, y, w, h)
x, y, w, h = rect

color = [random.randint(0, 255) for _ in range(3)]

degrees = 60
center = (x + w / 2), (y + h / 2)
rotation_matrix = cv.getRotationMatrix2D(center, degrees, 1)
rotated_image = cv.warpAffine(img, rotation_matrix, gray.shape[::-1])

cv.rectangle(rotated_image, (x, y), (x + w, y + h), color)

cv.imshow("Image", rotated_image)
cv.waitKey(0)

We first convert the image to gray scale. The color wheel in gray scale does not contain any values of pure white. We can therefore threshold the image at a high threshold, to segment the color wheel.

We then find contours in the image (which in this case only will be one contour), and find the bounding rectangle enclosing the contour. From this rectangle we can find the center point by the means of the top left corner, the height and width. We use this to create a rotation matrix, and call the affine warp function. Lastly, we draw a rectangle around the found contour. This is just for viewing pruposes.

We get the following result.

alt text

Although a perfectly fine solution, we cannot help but rotate the whole image. Here is a solution using cvhelper.

cvhelper:

import cv2 as cv
import cvhelper as cvh

img = cv.imread("resources/color_wheel_invert.png")
gray = cvh.bgr2gray(img)
otsu = cvh.threshold_binary(gray, 250, inverse=True)
contours = cvh.find_external_contours(otsu)
contour = contours[0]
rect = contour.bounding_rect  # Gives a Rect object
degrees = 60

center = rect.center  # Gives a Point object
top_left = rect.tl  # Gives a Point object
new_center = center - top_left 
img[rect.slice] = cvh.rotate_image(
    img[rect.slice], new_center, degrees, unit=cvh.AngleUnit.DEGREES
)
cvh.rectangle(img, rect, cvh.Color.RANDOM)

cv.imshow("Image", img)
cvh.wait_key(0)

We again follow the same approach. However, with the Contour class, we can simply call the bounding rect property. This yields a Rect object, which has a center property. Convenient.

Where we before were left with no (obvious) choice but to rotate the whole image, we can now simply slice the image at the rectangle, only rotating the figure itself. For this exact purpose, it doesn't make much different, but it is a demonstration. We find the new center from which to rotatet, and simply call the rotate image function. We can here choose whether to use degrees or radians. Lastly we draw a rectangle with a random color.

We get the following result.

alt text

Not only is this a tad less tedious to write, but we are also easily able to rotate only the relevant part of the circle by slicing. The contour, rectangle and point objects are also an ease to work with.

Other Area of Ease

While not providing examples, there are many other parts of the OpenCV that become an ease to work with, when using cvhelper. Areas include

  • Morphology
  • Image normalization
  • Color conversion
  • Thresholding
  • Image smoothing

Metadata

Release files for cvhelper 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cvhelper 0.1.0
File Size Uploaded
cvhelper-0.1.0.tar.gz 12.9 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for cvhelper 0.1.0
File Interpreter ABI Platform
cvhelper-0.1.0-py2.py3-none-any.whl Python 2, Python 3 none any Details

Total release size: 25.5 kB

Release files / cvhelper-0.1.0.tar.gz

Download URL cvhelper-0.1.0.tar.gz
Size 12.9 kB
Tags Source
SHA-256 checksum
How to use checksums
226fc99a5c315bd8987d35f85cf5ae3f811b74be758a723e70eca0201b1c6ddb
BLAKE2b-256 checksum
How to use checksums
c0f2e11a47e041d6b969b124da8b89115539afa7e3d3b3b3d25c0489c5160446
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.13.0 pkginfo/1.5.0.1 requests/2.19.1 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.7.0

Release files / cvhelper-0.1.0-py2.py3-none-any.whl

Download URL cvhelper-0.1.0-py2.py3-none-any.whl
Size 12.6 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
6e1cfe2c5b2601befedd117d12a6bc61f9ae5218f1a9a7a47f987f5d581184c0
BLAKE2b-256 checksum
How to use checksums
4e8182dc92948e37adf3e8fe0b082447351522e15d141798a2e52cf0414f9b4c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.13.0 pkginfo/1.5.0.1 requests/2.19.1 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.7.0

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page