基于Python的openCV笔记(1):numpy数组的基础使用
numpy数组的简易使用,若要直接使用原码需先将其他代码块注释(否则可能引起变量冲突),各个代码块以注释名称标识。
#-*- coding = utf-8 -*-
#@Time : 2021/1/31 12:25
#@Author : 夏帆
#@File : cv.py
#@Software : PyCharm
import cv2
import numpy
import os
import numpy as np
import matplotlib.pyplot as plt
#创建numpy数组实例
img = numpy.zeros((3,3),dtype=numpy.uint8)
print("1",img)
img = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
print("2",img)
#图像与原始字节转换
#创建随机原始字节
randombytearray = bytearray(os.urandom(120000))
flatnumpyarray = numpy.array(randombytearray)
#转化为灰度图片
grayimg = flatnumpyarray.reshape(300,400)
cv2.imwrite('gray.png',grayimg)
#转化为brg图片
colorimg = flatnumpyarray.reshape(100,400,3)
cv2.imwrite('bgr.png',colorimg)
也可直接用numpy方法进行初始化和重构
gray = numpy.random.randint(0,256,120000).reshape(300,400)
#设置左上角坐标的像素为白色,并显示输出
img = cv2.imread('gray.png')
img[0,0] = [255,255,255]
plt.imshow(img)
plt.show()
#使用item获取坐标像素引索位置(颜色通道)的值,使用itemset设置指定像素在指定颜色通道的值
img = cv2.imread('bgr.png')
print(img.item(50,120,0)) #第一个参数和第二个参数x和y构成坐标,第三个参数指定颜色通道
img.itemset((50,120,0),255) #前三个参数与item相同,第四个参数为改变颜色通道的参数的值
print(img.item(50,120,0))
#numpy.array获取图像属性
print(img.shape) #获得宽度、高度、通道数的数组
print(img.size) #获得图像像素的大小
print(img.dtype) #获得图像的数据类型
##关于numpy数组的直接使用
#将绿色通道的索引值置0
img = cv2.imread('bgr.png')
img[:,:,1] = 0
#设置区域,并对区域进行操作 roi为兴趣区域
roi = img[0:100,0:100]
plt.imshow(roi)
plt.show()
plt.imshow(img)
plt.show()
img[0:100,300:400] = roi
plt.imshow(img)
plt.show()