NumPy(Numerical Python) 是 Python语言的一个扩展程序库,支持大量的维度数组与矩阵运算,针对数组运算提供大量的数学函数库。N 维数组对象 ndarray是一系列同类型数据的集合,以 0 下标为开始进行集合中元素的索引。
import cv2 as cv
import numpy as np
def access_pixels(image):
print(image.shape)
height = image.shape[0]
width = image.shape[1]
channels = image.shape[2]
print('width : %s height : %s channels : %s' % (width, height, channels)) # 输出数值
# 遍历数组中的每个像素点
for row in range(height):
for col in range(width):
for c in range(channels):
# 获取数值
pv = image[row, col, c]
# 修改数组中像素点的值
image[row, col, c] = 255 - pv
cv.imshow('pixels_demo', image)
# 基于access_pixels计算的图像进行像素取反
def inverse(image):
# 按位取反就是将数值根据每个bit位1变0,0变1
dst = cv.bitwise_not(image)
cv.imshow('inverse demo', dst)
# 创建新的数组
def create_image():
"""
zeros(shape, dtype = float, order = 'C'):创建指定大小的数组,数组元素以 0 来填充
shape 数组形状
dtype 数据类型,可选
order 'C' 用于 C 的行数组,或者 'F' 用于 FORTRAN 的列数组
:return:
"""
img = np.zeros([400, 400, 3], np.uint8)
"""
ones(shape, dtype = None, order = 'C'):创建指定形状的数组,数组元素以 1 来填充
shape 数组形状
dtype 数据类型,可选
order 'C' 用于 C 的行数组,或者 'F' 用于 FORTRAN 的列数组
"""
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)
# 一个通道,第一种初始化为灰色的
img = np.zeros([400, 400, 1], np.uint8)
img[:, :, 0] = np.ones([400, 400]) * 127
cv.imshow('gray image', img)
# 一个通道,第二种初始化为黑色的
img = np.zeros([400, 400, 1], np.uint8)
img = img * 0
cv.imshow('black image', img)
# cv.imwrite('D:/OpenCV/opencv-python/xiexie.jpg', img)
# 打印二维数组
m1 = np.ones([3, 3], np.uint8)
# m1数组填充fill中的值
m1.fill(122.388)
print('m1 : %s'%m1)
# 打印一维数组
""""
reshape(arr, newshape, order='C'):不改变数据的条件下修改形状
arr:要修改形状的数组
newshape:整数或者整数数组,新的形状应当兼容原有形状
order:'C' - - 按行,'F' - - 按列,'A' - - 原顺序,'k' - - 元素在内存中的出现顺序。
"""
m2 = m1.reshape([1, 9])
print('m2 : %s'%m2)
"""
array(object, dtype):创建一个ndarray数组m3
object:数组或嵌套的数列
dtype:数组元素的数据类型;int8 字节(-128 to 127);int32 整数(-2147483648 to 2147483647)
"""
m3 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], np.int32)
m3.fill(9)
print('m3 : %s'%m3)
print("-------Hello Python-------")
src = cv.imread('D:/OpenCV/opencv-python/xiexie.png')
cv.namedWindow('input image', cv.WINDOW_AUTOSIZE)
cv.imshow('input image', src)
# getTickCount:返回从操作系统启动到当前所经的计时周期数
t1 = cv.getTickCount()
access_pixels(src)
inverse(src)
create_image()
t2 = cv.getTickCount()
# getTickFrequency:一秒内重复的次数
time = (t2 - t1) / cv.getTickFrequency()
# 1000 *总次数/一秒内重复的次数= 时间(ms)
print('time : %s ms' % (time * 1000))
cv.waitKey(0)
cv.destroyAllWindows()