Python + OpenCV 學習筆記(三)>>> Numpy 陣列操作
阿新 • • 發佈:2018-11-25
將影象畫素迭代取反:
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)
src = cv.imread("/home/pi/Desktop/apple.jpg" )
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
t1 = cv.getTickCount()
access_pixels(src)
t2 = cv.getTickCount()
print('time : %s' % ((t2-t1)/cv.getTickFrequency()))
cv.waitKey(0)
cv.destroyAllWindows()
整個程式跑完共耗時12s左右
建立影象
def create_image():
img = np. zeros([400, 400, 3], np.uint8) #返回來一個給定形狀和型別的用0填充的陣列
cv.imshow('new image', img)
對指定維數進行賦值:
def create_image():
img = np.zeros([400, 400, 3], np.uint8)
img[:, :, 0] = np.ones([400, 400])*255 #返回來一個給定形狀和型別的用1填充的陣列,再乘以255,因為0 通道是藍色,所以乘以255 就顯示藍色
cv.imshow('new image', img)
若將img[:, :, 0]
中0 改為1 或2,則輸出綠色或紅色影象
建立單通道影象,每個畫素點都是127,即灰度圖
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) * 127 #一定要宣告畫素值型別,否則預設全為1
cv.imshow('new image', img)
呼叫庫函式實現畫素取反:
def inverse(image):
dst = cv.bitwise_not(image) #二進位制資料進行“非”操作
cv.imshow("取反", dst)
該操作比對每個畫素點進行取反速度快很多
建立矩陣:
m1 = np.ones([4, 4], np.int32)
m1.fill(43.22)
print(m1)
m2 = m1.reshape([1, 16])
print(m2)
m3 = np.array([[1,2,3], [4,5,6], [7,8,9]], np.uint32)
m3.fill(9)
print(m3)