OpenCV 的帮助程序包
项目描述
opencv-python 的简单帮助程序包
cvhelper 是 opencv-python 包的更简单的包装器。如前所述,包仅提供对 OpenCV 函数的访问权限,在 C++ 风格中,编写起来可能很乏味。也不支持 OpenCV 类,如 Rect、Point 等。cvhelper 试图解决这个问题。
包处于早期状态,欢迎投稿!该软件包的内容是一个供需模型,其中添加了功能,因为在 opencv-python 中发现了新的乏味事物。不要犹豫提出问题,请求新功能或增强建议!
安装
由 python 包管理器 pip 安装。
pip install cvhelper
这也会安装依赖项opencv-python,opencv-contrib-python和numpy,如果不存在的话。
例子
阅读视频
这段代码不言自明。
香草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()
简历助手:
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
旋转色轮
假设我们有以下要旋转的色轮图像。
我们当然想在它的中心旋转它,而不是在图像的中心。使用 OpenCV 的可能解决方案是
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)
我们首先将图像转换为灰度。灰度色轮不包含任何纯白色值。因此,我们可以以高阈值对图像进行阈值化,以分割色轮。
然后我们在图像中找到轮廓(在这种情况下只有一个轮廓),并找到包围轮廓的边界矩形。从这个矩形中,我们可以通过左上角的高度和宽度找到中心点。我们使用它来创建一个旋转矩阵,并调用仿射扭曲函数。最后,我们在找到的轮廓周围画一个矩形。这只是为了查看目的。
我们得到以下结果。
虽然是一个完美的解决方案,但我们还是忍不住要旋转整个图像。这是使用 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)
我们再次遵循相同的方法。但是,使用 Contour 类,我们可以简单地调用边界矩形属性。这将产生一个 Rect 对象,该对象具有 center 属性。方便的。
之前我们没有(明显的)选择,只能旋转整个图像,现在我们可以简单地在矩形处切片图像,只旋转图形本身。对于这个确切的目的,它并没有太大的不同,但它是一个演示。我们找到要旋转的新中心,然后简单地调用旋转图像函数。我们可以在这里选择是使用度数还是弧度。最后我们绘制一个随机颜色的矩形。
我们得到以下结果。
这不仅写起来不那么乏味,而且我们还可以通过切片轻松地仅旋转圆的相关部分。轮廓、矩形和点对象也很容易使用。
其他轻松领域
虽然没有提供示例,但在使用 cvhelper 时,OpenCV 的许多其他部分变得易于使用。领域包括
- 形态学
- 图像归一化
- 颜色转换
- 阈值化
- 图像平滑
项目详情
下载文件
下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。