一、遍歷圖片像素
import cv2 as cv
#函數(shù)——遍歷像素取反后顯示圖片
def access_pixels(image):
????width = image.shape[0]
????height = image.shape[1]
????channels = image.shape[2]
????print("width = %s,height = %s,channels = %s"%(width,height,channels))
????for iin range(width):
????????for jin range(height):
????????????for kin range(channels):
????????????????pv = image[i,j,k]
????????????????image[i,j,k]=255-pv
? ? ? ? ? cv.imshow("pixels_b",image)
#載入并顯示圖片
img = cv.imread("D:/temp/img/f1.jpg")
cv.imshow("Image",img)
#調(diào)用函數(shù)
access_pixels(img)
#等待鍵盤輸入并關(guān)閉所有窗口
cv.waitKey(0)
cv.destroyAllWindows()
二、創(chuàng)建一張新圖,使用通道及像素簡單控制其色彩
1、創(chuàng)建一張3通道新圖
import cv2 as cv
import? numpy as np
pic = np.zeros([666,666,3],np.uint8)? #創(chuàng)建一個3通道膳凝,第一個參數(shù)是形狀,第二個是類型
pic[:,:,2] = np.ones([666,666])*255? #通過控制通道和像素值確定呈現(xiàn)的色彩
cv.imshow("new_pic",pic)
cv.waitKey(0)
cv.destroyAllWindows()
2、創(chuàng)建一張單通道新圖
import cv2 as cv
import? numpy as np
pic = np.zeros([666,666,1],np.uint8)
pic[:, :, 0] = np.ones([666, 666]) *127? #單通道127對應(yīng)灰色
cv.imshow("new_pic",pic)
cv.waitKey(0)
cv.destroyAllWindows()
三壶愤、知識點整理
1、zeros和ones
np.zeros(size,dtype) 可以創(chuàng)建任意維度的數(shù)組馏鹤,新建圖片內(nèi)所有像素值均為0
np.ones(size,dtype) 可以創(chuàng)建任意維度的數(shù)組征椒,新建圖片內(nèi)所有像素值均為1
以下代碼:
pic = np.zeros([666,666,1],np.uint8)
pic[:, :, 0] = np.ones([666, 666]) *127
可以單使用ones代替為:
pic = np.ones([666, 666, 1],np.uint8)*127
2、Numpy數(shù)組的基本操作
m1 = np.ones([3,3],np.float32)? #新建一個3行3列的數(shù)組湃累,數(shù)據(jù)類型為float32
m1.fill(12222.38)? #m1數(shù)組中所有值都賦值為12222.38
print(m1)
m2 = m1.reshape([1,9])? #把m1變?yōu)?行9列的數(shù)組m2
3勃救、計算函數(shù)執(zhí)行時間
在本文一中加入以下代碼,可計算函數(shù)執(zhí)行所需時間:
t1 = cv.getTickCount()
access_pixels(src)#需要測試時間的函數(shù)
t2 = cv.getTickCount()
time = (t2-t1)/cv.getTickFrequency()5print("time : %s ms"%(time*1000))
4治力、python中像素取反的基本操作
本文一中像素取反的函數(shù)效率低蒙秒,實際編程中直接調(diào)用python中已有的API可極大提升效率。
access_pixels(image)函數(shù)可改為以下函數(shù):
def inverse(image):
? ? des = cv.bitwise_not(image)
? ? cv.imshow("inverse demo",des)