Python's opencv core module core common functions

import time

import cv2 as cv
import numpy as np

pathD = r'C:\Users\11010\Desktop'
path = r'C:\Users\11010\Desktop\a.jpg'


# 使用numpy创建矩阵,使用cv显示
def matdemo():
    # 创建全0矩阵
    m1 = np.zeros([512, 512], dtype=np.uint8)
    m1[:] = 128  # 所有值初始化为128
    m1[120:300, 120:300] = 0  # 修改部分区域
    cv.imshow('m1', m1)  # 显示图像
    cv.waitKey(0)
    cv.destroyAllWindows()  # 销毁窗口


# 调整图像大小
def resizeImage():
    img = cv.imread(path, cv.IMREAD_COLOR)
    print('img的类型:', type(img))

    # 获取图像的尺寸与通道
    shape = img.shape
    rows = shape[0]
    cols = shape[1]
    channels = shape[2]
    print('img rows:', rows)
    print('img cols', cols)
    print('img channels', channels)

    # 调整图像尺寸
    mask = np.ones(shape, dtype=np.uint8)  # 创建掩模
    m3 = cv.copyTo(img, mask)  # 图像拷贝
    m3 = cv.resize(m3, (int(rows / 2), int(cols / 2)))  # 图像尺寸调整
    cv.imshow('m3', m3)
    cv.waitKey(0)
    cv.destroyAllWindows()


# 使用point结构 :python中用tuple表示point
def pointDemo():
    pt = (10, 20)  # 表示点
    print('pt 类型', type(pt))

    # 点乘
    pt2 = (1, 2)
    res = np.dot(pt, pt2)
    print('dot 结果:', res)

    # 叉乘
    pt3 = (1, 0, 0)
    pt4 = (0, 1, 0)
    pt5 = np.cross(pt3, pt4)
    print('cross结果:', pt5)


# 四则运算与位运算: 加、减、乘、除、位与、位或、异或、非
def mtDemo():
    # 创建矩阵
    m1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    m2 = np.array([[77, 88, 67], [12, 15, 16], [17, 18, 29]])

    # 矩阵加法
    m_add = cv.add(m1, m2)
    print('m1+m2=', m_add)
    # 矩阵减法
    m_sub = cv.subtract(m2, m1)
    print('m2-m1', m_sub)
    # 矩阵乘法
    m_mul = cv.multiply(m1, m2)
    print('m1xm2', m_mul)
    # 矩阵除法
    m_div = cv.divide(m2, m1)
    print('m2/m1', m_div)

    # 也可以直接写四则符号进行运算
    print(m1 + m2)
    print(m1 - m2)
    print(m1 * m2)
    print(m2 / m1)

    # 按位与
    m_and = cv.bitwise_and(m1, m2)
    print('m_and', m_and)
    # 按位或
    m_or = cv.bitwise_or(m1, m2)
    print('m_or=', m_or)
    # 异或运算
    m_orx = cv.bitwise_xor(m1, m2)
    print('m_orx', m_orx)
    # 非运算
    m_not = cv.bitwise_not(m1)
    print('m-not', m_not)


# 代数运算
def dsDemo():
    m = np.array([[9., 9.], [9., 4.]])
    # 计算矩阵均值
    mean_result = cv.mean(m)
    print('矩阵均值:', mean_result)

    # 对矩阵做归一化
    dst = np.array([])
    # normalize对矩阵做归一化,参数含义为输入矩阵、输出结果、归一化上下界
    norm_res = cv.normalize(m, dst, norm_type=cv.NORM_MINMAX)
    print('归一化', norm_res)

    # 对矩阵平方根运算
    msqrt = cv.sqrt(m)
    print('矩阵平方根:', msqrt)
    # 幂运算
    mpow = cv.pow(m, 3)
    print('矩阵幂运算', mpow)
    # 指数运算
    mexp = cv.exp(m)
    print('矩阵指数运算', mexp)
    # 对数运算
    mlog = cv.log(m)
    print('对数运算:', mlog)


# 比较运算
def mcompare():
    # 创建矩阵
    m1 = np.array([[1, 2], [3, 4]])
    m2 = np.array([[3, 2], [5, 4]])
    # 比较两个矩阵是否相等,在比较时会按位置依次对矩阵的每一个值进行比较,相等则该位置的值为255,否则为0
    comb = cv.compare(m1, m2, cv.CMP_EQ)  # CMP_EQ用于指定比较规则,比较矩阵是否相等
    print('矩阵比较结果:', comb)
    # 求最大值
    max = cv.max(m1, m2)
    print('max:', max)
    # 求最小值
    min = cv.min(m1, m2)
    print('min: ', min)
    # 求最小值、最大值、最小值的坐标、最大值的坐标
    mmp = cv.minMaxLoc(m1)
    print("mmp=", mmp)
    # 对矩阵排序
    msort = cv.sort(m1, cv.SORT_ASCENDING)  # 升序
    print('矩阵升序后:', msort)


# 矩阵的特征值与特征向量
def meigen():
    m = np.array([[1., 2.], [3., 4.]])
    eigen_result = cv.eigen(m)
    # 返回的三个结果分别表示: 是否可计算特征值与特征向量、特征值、特征向量
    print('特征值与特征向量:', eigen_result)
    # 计算非对称矩阵的特征值与特征向量
    ehs = cv.eigenNonSymmetric(m)
    print('非对称矩阵特征值与特征向量:\n', ehs)


# 随机数矩阵
def randomAx():
    dst = np.zeros((3, 3), np.int8)  # 构建全0矩阵

    # 生成服从正态分布的矩阵,参数含义为:输出的随机矩阵、均值、随机数的标准差
    cv.randn(dst, 3, 1)
    print('正态分布随机矩阵: \n', dst)

    dst2 = np.zeros((4, 4), np.int8)  # 构建全0矩阵
    # 生成服从均匀分布的矩阵
    cv.randu(dst2, 1, 100)
    print('均匀分布的矩阵:\n', dst2)


# 矩阵变换
def atoreduce():
    img = cv.imread(path)
    print('图片形状:', img.shape)

    # 矩阵转向量,参数含义为: 输入图像、降维的维度、降维操作
    dst = cv.reduce(img, 0, cv.REDUCE_MAX)
    print('矩阵转向量之后的形状:', dst.shape)


# 通道合并与分离
def mchannel():
    img = cv.imread(path)
    # 颜色空间分离: 一副RGB格式的图像,包括R、G、B 3个通道
    b, g, r = cv.split(img)
    # 显示每个通道的图像
    cv.imshow('b', b)
    cv.imshow('g', g)
    cv.imshow('r', r)

    # 通道合并
    merge_m = cv.merge([b, g, r])
    cv.imshow('merge', merge_m)

    cv.waitKey(0)
    cv.destroyAllWindows()


# 图像旋转
def mflip():
    img = cv.imread(path)
    flip_x = cv.flip(img, 0)  # 沿x轴旋转
    flip_y = cv.flip(img, 1)  # 沿y轴旋转
    flip_xy = cv.flip(img, -1)  # 沿x、y轴旋转
    rotate_90 = cv.rotate(img, cv.ROTATE_90_CLOCKWISE)  # 按角度顺时针旋转90°
    rotate_180 = cv.rotate(img, cv.ROTATE_180)  # 按角度顺时针旋转180°
    rotate_270 = cv.rotate(img, cv.ROTATE_90_COUNTERCLOCKWISE)  # 逆时针旋转90°

    # 显示图像
    cv.imshow('x', flip_x)
    cv.imshow('y', flip_y)
    cv.imshow('xy', flip_xy)
    cv.imshow('90', rotate_90)
    cv.imshow('180', rotate_180)
    cv.imshow('270', rotate_270)

    cv.waitKey(0)
    cv.destroyAllWindows()


# 图像拼接
def imageConect():
    img = cv.imread(path)
    img2 = cv.imread(path)
    # 水平拼接图像
    hv = cv.hconcat([img, img2])
    # 垂直拼接图像
    vh = cv.vconcat([img, img2])
    # 图像显示
    cv.imshow('水平拼接', hv)
    cv.imshow('垂直拼接', vh)

    cv.waitKey(0)
    cv.destroyAllWindows()


# 图像边界拓展
def imageBoder():
    img = cv.imread(path)
    # 边界拓展,参数函数含义为:输入图像、上、下、左、右边框尺寸、图像边界拓展策略、边框像素值
    bcons = cv.copyMakeBorder(img, 30, 30, 30, 30, cv.BORDER_CONSTANT, value=88)

    cv.imshow('图像扩展', bcons)
    cv.waitKey(0)
    cv.destroyAllWindows()


# 傅里叶变换
def mdft():
    img = cv.imread(path, 0)
    img_f = np.float32(img)  # float形式转换
    dft_img = cv.dft(img_f)  # 执行傅里叶变换
    # 结果显示
    cv.imshow('原图', img)
    cv.imshow('傅里叶转换后的图', dft_img)

    cv.waitKey(0)
    cv.destroyAllWindows()


# 图像像素遍历: 图像在内存中是以矩阵的形式存储的,图像像素的遍历就是对矩阵的遍历
def mmatrix(img):
    height = img.shape[0]
    width = img.shape[1]
    channes = img.shape[2]
    print('w: %s,h: %s,chanel: %s' % (width, height, channes))

    # 使用暴力遍历矩阵,使用切片遍历像素效率更高: img[:]=255-img[:]
    for row in range(height):  # 遍历高
        for col in range(width):  # 遍历宽
            for c in range(channes):  # 遍历通道
                px = img[row, col, c]
                # 按像素值取反
                img[row, col, c] = 255 - px

    cv.imshow('转换后的颜色', img)
    cv.waitKey(0)
    cv.destroyAllWindows()


# 使用切片遍历图像矩阵
def mmatrix2(img):
    # 使用切片遍历像素效率更高: img[:]=255-img[:]
    img[:] = 255 - img[:]  # 取反操作
    cv.imshow('转换后的颜色', img)
    cv.waitKey(0)
    cv.destroyAllWindows()


# 提取拍照手写签名
def imageText(img):
    height = img.shape[0]
    width = img.shape[1]
    channes = img.shape[2]
    print('w: %s,h: %s,chanel: %s' % (width, height, channes))

    # 使用暴力遍历矩阵,使用切片遍历像素效率更高: img[:]=255-img[:]
    for row in range(height):  # 遍历高
        for col in range(width):  # 遍历宽
            for c in range(channes):  # 遍历通道
                # 去除背景
                if img[row, col, c] > 100:
                    # 将背景变为纯白色
                    img[row, col, c] = 255
                # 文字加黑
                if img[row, col, c] < 100:
                    # 将文字变为纯黑色
                    img[row, col, c] = 0
    cv.imshow('转换后的颜色', img)
    cv.waitKey(0)
    cv.destroyAllWindows()


# matdemo()
# resizeImage()
# pointDemo()
# mtDemo()
# dsDemo()
# mcompare()
# meigen()
# randomAx()
# atoreduce()
# mchannel()
# mflip()
# imageConect()
# imageBoder()
# mdft()

# img = cv.imread(path)  # 读取图像
# start = time.time()  # 开始记录时间
# mmatrix(img)  # 执行图像的矩阵遍历操作
# end = time.time()  # 结束记录时间
# print('耗时 %s 秒' % (end - start))  # 输出耗时
#
# img2 = cv.imread(path)  # 读取图像
# start2 = time.time()  # 开始记录时间
# mmatrix2(img2)  # 执行图像的矩阵遍历操作
# end2 = time.time()  # 结束记录时间
# print('耗时 %s 秒' % (end2 - start2))  # 输出耗时

img = cv.imread(pathD + '\p.png')
imageText(img)

Guess you like

Origin blog.csdn.net/XiaoWang_csdn/article/details/131019862