今天学习像素的遍历,反转,以及numpy的基本操作。
用法:zeros(shape, dtype=float, order='C')
返回:返回来一个给定形状和类型的用0填充的数组;
参数:shape:形状
dtype:数据类型,可选参数,默认numpy.float64
dtype类型:t ,位域,如t4代表4位
b,布尔值,true or false i,整数,如i8(64位)u,无符号整数,u8(64位)
f,浮点数,f8(64位)c,浮点负数,o,对象,s,a,字符串,s24
u,unicode,u24 order:可选参数,c代表与c语言类似,行优先;F代表列优先
以上借鉴于帮助文档的翻译
img[:, :, 2] = np.ones([400,400]) * 255
# img[:,:,2]是一种切片方式,冒号表示该维度从头到尾全部切片取出
# 所以img[:,:,2]表示切片取出所有行,所有列的第三个通道(索引为2)
# 右侧首先创建了一个400*400的二维数组,元素初始化为1,再乘上255,所有元素变为255
# 注意右侧400*400的二维数组与左侧切片部分形状相同,所以可以赋值
# 即所有行,所有列的第三个通道(R)的值都变为255,一二通道(BG)仍为0,即所有像素变为红色BGR(0,0,255)
下面都是常规操作,注释于代码
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)
#上述自定义函数的功能是像素取反,当然,opencv自带像素取反方法bitwise_not(),不需要这么麻烦
def inverse(img):
"""此函数与access_pixels函数功能一样"""
image1 = cv.bitwise_not(img)
cv.imshow("pixels_demo",image1)
def creat_image(): #通过像素点创建自己的图片
img = np.zeros([400,400,3],np.uint8) #返回来一个给定形状和类型的用0填充的数组
'''zeros(shape, dtype=float, order='C')'''
5)
cv.imshow("NEW",img)
cv.imwrite("C:/Users/idmin/Desktop/img/img2.jpg",img)
src = cv.imread("C:/Users/idmin/Desktop/img/img1.jpg") #blue,green,red
#cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
t1 = cv.getTickCount()#得到当前的时间片
#access_pixels(src)
inverse(src)
creat_image()
t2 = cv.getTickCount()
time = (t2-t1)/cv.getTickFrequency()
print("time:%s ms"%(time*1000)) #直接求得的时间是秒
cv.waitKey(0)
cv.destroyAllWindows() # 关闭所有窗口
运行效果: