初学OpenCV(二)
修改图像属性
import cv2 as cv
import numpy as np
# 三个通道的顺序 blue,green,red
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): # 循环从0到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) # 第一个参数为窗口名称
print("--------Hello Python--------")
src = cv.imread("D:/5.jpg")
t1 = cv.getTickCount()
access_pixels(src)
t2 = cv.getTickCount()
time = (t2-t1)/cv.getTickFrequency() # cv.getTickFrequency()一秒内重复的次数
print("time : %s ms"%(time*1000))
cv.waitKey(0)
cv.destroyAllWindows()
getTickCount():用于返回从操作系统启动到当前所经的计时周期数,也可以这么理解,get Tick Count(s)。
getTickFrequency():用于返回CPU的频率。get Tick Frequency。这里的单位是秒,也就是一秒内重复的次数。
总次数/一秒内重复的次数 = 时间(s)
1000 *总次数/一秒内重复的次数= 时间(ms)
getTickCount()和getTickFrequency()说明
创建图像
import cv2 as cv
import numpy as np
def creat_image():
img = np.zeros([400,400,3],np.uint8) # 创建400*400的3通道图像
img[:,:,0] = np.ones([400,400])*255 #修改通道值,修改的是第一个通道的值
cv.imshow("new image",img)
"""
创建单通道的图像
img = np.zeros([400,400,1],np.uint8)
img[:,:,0] = np.ones([400,400])*127
cv.imshow("new image",img)
也可以用ones()进行初始化,这样更灵活
img = np.ones([400,400,1],np.uint8)
img = img *127
cv.imshow("new image",img)
"""
"""
初始化二维的
m1 = np.ones([3,3],np.float32)
m1.fill(122.666)
print(m1)
m1.reshape([1,9])
print(m1)
"""
# 三个通道的顺序blue,green,red
t1 = cv.getTickCount()
creat_image()
t2 = cv.getTickCount()
time = (t2-t1)/cv.getTickFrequency()
print("time : %s ms"%(time*1000))
cv.waitKey(0)
cv.destroyAllWindows()