1、可以通过np创建数组,典型的代码为:
img = np.zeros([H,W,C],np.uint8)
img = np.ones([H,W,C],np.uint8)
#引入opencv模块
import cv2 as cv
#引入numpy模块
import numpy as np
#引入sys模块
import sys
#读取并输出图像像素值
def showimagepixel(img):
#输出图像像素
pixel_data=np.array(img)
print(pixel_data)
#对图像的像素值进行操作
def pixel_process(img):
H,W,C = img.shape #该方法可以获取图像的尺寸
print("height: %s, width: %s, channel: %s,"%(H,W,C))
for row in range(W):
for col in range(H):
for channel in range(C):
pv = img[row,col,channel]
img[row,col,channel]=255-pv
return img
def pixel_test():
img = cv.imread('E:/chenopencvblogimg/red.bmp')
#判断是否读取成功
if img is None:
print("Could not read the image,may be path error")
return
#显示原始图像
cv.namedWindow("display_orign",cv.WINDOW_NORMAL)
cv.imshow("display_orign", img)
showimagepixel(img)
#显示处理后的图像
imgprocessed = pixel_process(img)
cv.namedWindow("display_processed",cv.WINDOW_NORMAL)
cv.imshow("display_processed", imgprocessed)
showimagepixel(imgprocessed)
#让显示等待键盘输入维持在那里,否则程序跑完就闪退啦!
cv.waitKey(0)
#销毁窗口
cv.destroyAllWindows()
if __name__ == '__main__':
sys.exit(pixel_test() or 0)
2、np数据的reshape
#引入opencv模块
import cv2 as cv
#引入numpy模块
import numpy as np
#引入sys模块
import sys
def img_test():
img = np.ones([4,4],np.uint8)
print(img)
img.fill(127)
print(img)
img2 = img.reshape([1,16])
print(img2)
#让显示等待键盘输入维持在那里,否则程序跑完就闪退啦!
cv.waitKey(0)
#销毁窗口
cv.destroyAllWindows()
if __name__ == '__main__':
sys.exit(img_test() or 0)