Python-Opencv学习(2)——Numpy的基本操作

获取图像的高宽

Numpy可遍历数组中的每个像素点,可以修改数组中的像素点的值

# 获取图像的高、宽和通道
def access_pixels(image):
    print(image.shape)
    height = image.shape[0]
    width = image.shape[1]
    # channels = image.shape[2]
    # 在彩色图像中才有通道,此处是灰度图
    print("width : %s,height : %s" % (width, height))

Opencv中RGB彩色图像的顺序是BGR(Blue、Green、Red)

遍历并修改像素

for row in range(height):
    for col in range(width):
        pv = image[row, col]  # 遍历
        image[row, col] = 255-pv

但是,这种方法的耗时有点长,可以用下面的API:

# 和上面的函数实现功能一样,可以反转图像,但是速度更快
def inverse(image):
    dst = cv.bitwise_not(image)
    cv.imshow("inverse", dst)

计时

cv.getTickCount() 和 cv.getTickFrequency()来实现计时的功能

t1 = cv.getTickCount()

t2 = cv.getTickCount()
time = (t2-t1)/cv.getTickFrequency()
print("Time : %s ms" % (time*1000))   # 这里用毫秒来表示,用秒就去掉*1000

创建新的图像并修改

初始化图像的两种方法:
一个是用zeros(),把图像全部变成0(黑色);
一个是用ones(),把图像全部变成1(白色)。

多通道

# 创建新的图像, 并修改
def create_image():
    img = np.zeros([400, 400, 3], np.uint8)
    img[:, :, 0] = np.ones([400, 400])*255  # 修改第一个通道Blue
    # img[:, :, 1] = np.ones([400, 400]) * 255  # 修改第两个通道Green
    # img[:, :, 2] = np.ones([400, 400]) * 255  # 修改第三个通道Red
    cv.imshow("new image", img)

创建了一幅黑色图像

在这里插入图片描述

修改第一个通道的值,结果如下(蓝色)

在这里插入图片描述

单通道

def create_image_single():
    # img = np.zeros([400, 400, 1], np.uint8)
    # img[:, :, 0] = np.ones([400, 400])*127
    # 或者用下面这两行
    img = np.ones([400, 400, 1], np.uint8)
    img = img * 127
    cv.imshow("new image", img)

在这里插入图片描述

创建矩阵

def fill_in():
    m1 = np.ones([3, 3], np.float) # 注意这里的类型
    m1.fill(122.388)
    print(m1)

输出结果为:
[[122.388 122.388 122.388]
[122.388 122.388 122.388]
[122.388 122.388 122.388]]

将float改为uint8:

def fill_in():
    m1 = np.ones([3, 3], np.uint8)
    m1.fill(122.388)
    print(m1)

结果变成整型
[[122 122 122]
[122 122 122]
[122 122 122]]

类型要选择合适,看这个例子:

def fill_in():
    m1 = np.ones([3, 3], np.uint8)
    m1.fill(12238.8)
    print(m1)

此时被截断,只能输出:
[[206 206 206]
[206 206 206]
[206 206 206]]

因此,类型要选择合适,避免发生如上的截断情况,导致后续处理达不到效果
避免溢出,可以用cv.convertScaleAbs( )

维度之间的变换

用reshape(),但是数据不能变,1* 9不可能变成2* 5

# 创建矩阵
def fill_in():
    m1 = np.ones([3, 3], np.uint8)
    m1.fill(122.388)
    print(m1)
    # 维度变换
    m2 = m1.reshape([1, 9])
    print(m2)

猜你喜欢

转载自blog.csdn.net/weixin_45738316/article/details/109073659