import cv2 as cv
import numpy as np
def access_pixels(image):
#image.shape输出了image的三维数据:高,宽,通道
print(image.shape)
height = image.shape[0]
width = image.shape[1]
channels = image.shape[2]
print("height :%s, width :%s,channels : %s" %(width,height,channels))
for row in range(height):
#从0到height循环 类比于for(int row =0; row<height;row++)
for col in range(width):
for c in range(channels):
pv = image[row,col,c]#获取位于[row,col,c]坐标的像素值
image[row,col,c] = 255 -pv
cv.imshow("1",image)
def creat_image():
"""""
#建立多通道数组
#zeros(shape, dtype=float, order='C')
#依据给定形状和类型(shape, dtype, order])返回一个新的元素全部为0的数组(类比np.ones())。
#参数一:形状(即[row,col,channels])
#参数二:数据类型(默认是np.float64)
img = np.zeros([400,400,3],np.uint8) #这个输出的应该是400个400*3矩阵(400行400列每列3通道矩阵)
#ones(shape,dtype):依据给定形状和类型(shape,dtype),返回一个新的元素全部为1的数据
举个例子:print np.ones((4,5,3),dtype=np.uint8)
输出的是4(height)个5(width)X3(channel)矩阵,且所有元素为1
[ [1,1,1] [1,1,1] [1,1,1] [1,1,1] [1,1,1]
[1,1,1] [1,1,1] [1,1,1] [1,1,1] [1,1,1]
[1,1,1] [1,1,1] [1,1,1] [1,1,1] [1,1,1]
[1,1,1] [1,1,1] [1,1,1] [1,1,1] [1,1,1] ]
#该句话的意思就是令img的第2通道(G通道)赋值为255
img[:,:, 2] =np.ones([400, 400])*255
cv.imshow("2",img)
"""""
#建立单通道数组
img = np.zeros([400,400,1],np.uint8)
#img[:,:,0] = np.ones([400,400])*127
#对于单通道 也可以这么做,也就是单通道矩阵像素*127 ;但是如果是多通道,则是三通道矩阵
# 的像素*127
#img = img*127 与img.fill(127)作用是一样的
img.fill(127)
cv.imshow("3",img)
# cv.imwrite("E:/opencv/picture/img111.jpg",img)
src = cv.imread("E:/opencv/picture/test1.jpg")
cv.imshow("window",src)
t1 = cv.getCPUTickCount()#cv.getCPUTickCount 获取当前cpu到该位置所用的时间的总数
creat_image()
t2 = cv.getCPUTickCount()
time = (t2-t1)/cv.getTickFrequency()#计算得到creat_image()所用的时间(单位是us)
print("time : %s ms"%(time*1000))
cv.waitKey(0)
小结:
1. image.shape 得到image的外形尺寸:height,width,channel,其中image[0]是height, image[1]是width,, image[2]是channel
2. 逐个像素点改变像素值 利用三个for嵌套
3. 创建image的两种方法:
np.zeros(shape, dtype=float, order='C')
np.ones(shape,dtype)
当然也可以建立一个数组:
hsv = np.array([20,30,33]) 建立了一个3维数组
4. 给图片的某个通道赋值:
img[;,;,2] =np.ones([400,400])*255
补充:
我们利用access_pixel修改像素耗时太长了,这显然是我们不想看到的。下面用一句api指令就可以替代我们defination
def inverse(image):
dst = cv.bitwise_not(image)
cv.imshow("4",dst)
cv.bitwise_not(src) :
是对二进制数据进行“非”操作,即对图像(灰度图像或彩色图像均可)每个像素值进行二进制“非”操作,~1=0,~0=1
然后我们再计算时间就会发现节省了很多时间。
5. 计算某段代码所用时间
t1 = cv.getCPUTickCount()
api指令。。。
t2 = cv.getCPUTickCount()
time = (t2-t1)/cv.getTickFrequency()#计算得到