学习视频:python+opencv3.3视频教学 基础入门
其他学习记录:
Python+OpenCV(一)——基础操作
Python+OpenCV(二)——Numpy模块
Python+OpenCV(三)——色彩空间
Python+OpenCV(四)——像素运算
Python+OpenCV(五)——ROI和泛洪填充
Python+OpenCV(六)——均值/中值/自定义/高斯模糊、高斯噪声处理、高斯双边滤波
Python+OpenCV(七)——直方图及其应用
Python+OpenCV(八)——图像二值化
Python+OpenCV(十)——Canny边缘提取
Python+OpenCV(十一)——直线检测、圆检测
Python+OpenCV(十二)——轮廓发现
Python+OpenCV(十三)——对象测量
Python+OpenCV(十四)——膨胀与腐蚀
Python+OpenCV(十五)——开闭操作
Python+OpenCV(十六)——顶帽、黑帽
Python+OpenCV(十七)——人脸识别
Python+OpenCV(十八)——数字/字母验证码识别
源码如下:
# -*- coding = utf-8 -*-
# @Time : 2021/8/3 15:26
# @Author : 西兰花
# @File : OpenCV09.py
# @Software : PyCharm
import cv2 as cv # 引入OpenCV模块
import numpy as np
"""
图像金字塔
expand=扩大+卷积
reduce=高斯模糊+降采样
"""
def pyramid_demo(image):
level = 3
temp = image.copy()
pyramid_images = []
for i in range(level):
dst = cv.pyrDown(temp)
pyramid_images.append(temp)
cv.imshow("pyramid_demo_" + str(i), dst)
temp = dst.copy()
return pyramid_images
# def lapalian_pyramid_demo(image):
# pyramid_images = pyramid_demo(image)
# level = len(pyramid_images)
# for i in range(level - 1, -1, -1): # 从后向前
# expand = cv.pyrUp(pyramid_images[i], dstsize=image.shape[:2]) # 上采样
# lpls = cv.subtract(image[i-1], expand) # 利用高斯金字塔上一个减去当前采样获取的结果,得到拉普拉斯金字塔
# cv.imshow("lapls_down_%s"+str(i), lpls)
"""
图像梯度
"""
def lapalian_gradient_demo(image): # 拉普拉斯算子
kernel = np.array([[1, 1, 1], [1, -8, 1], [1, 1, 1]])
dst = cv.filter2D(image, cv.CV_32F, kernel=kernel)
lpls = cv.convertScaleAbs(dst)
cv.imshow("lapalian_gradient_demo", lpls)
def sobel_demo(image):
# grad_x = cv.Sobel(image, cv.CV_32F, 1, 0) # sobel(索贝尔)边缘检测
# grad_y = cv.Sobel(image, cv.CV_32F, 0, 1)
grad_x = cv.Scharr(image, cv.CV_32F, 1, 0) # scharr(莎尔)边缘检测
grad_y = cv.Scharr(image, cv.CV_32F, 0, 1)
gradx = cv.convertScaleAbs(grad_x)
grady = cv.convertScaleAbs(grad_y)
cv.imshow("gradient-x", gradx)
cv.imshow("gradient-y", grady)
print("------ Hello OpenCV ------")
src = cv.imread("C:/Users/Administrator/Pictures/PS/1.jpg") # 读取图像
cv.imshow("input image_1.jpg", src) # 显示图像
# pyramid_demo(src)
# lapalian_pyramid_demo(src)
# lapalian_gradient_demo(src)
sobel_demo(src)
cv.waitKey(0)
cv.destroyAllWindows() # 销毁/关闭所有窗口
输出结果:
1.图像金字塔
在用拉普拉斯方法计算图像金字塔时报错,且暂时为解决,以下是报错信息:
expand = cv.pyrUp(pyramid_images[i], dstsize=image.shape[:2]) # 上采样
cv2.error: OpenCV(3.4.2) C:\Miniconda3\conda-bld\opencv-suite_1534379934306\work\modules\imgproc\src\pyramids.cpp:996: error: (-215:Assertion failed) std::abs(dsize.width - ssize.width*2) == dsize.width % 2 && std::abs(dsize.height - ssize.height*2) == dsize.height % 2 in function 'cv::pyrUp_'