opencv-基础知识
色彩空间转换
import cv2
import numpy as np
def callback(userdata):
pass
###创建窗口
cv2.namedWindow('color',cv2.WINDOW_NORMAL)
###读取本地一张图片
img = cv2.imread("C:\\Users\dazhi\Desktop\-4113ee2870ecf076.jpg")
# img = cv2.imdecode(np.fromfile(r"C:\\Users\dazhi\Desktop\-4113ee2870ecf076.jpg",dtype=np.uint8),1)
# colorspaces = [cv2.COLOR_BGR2RGBA, cv2.COLOR_BGR2BGRA,
# cv2.COLOR_BGR2GRAY, cv2.COLOR_BGR2HSV,
# cv2.COLOR_BGR2YUV]
colorspaces = [cv2.COLOR_BGR2RGBA,cv2.COLOR_BGR2BGRA,cv2.COLOR_BGR2GRAY,
cv2.COLOR_BGR2HSV_FULL,cv2.COLOR_BGR2YUV]
###创建Trackbar
cv2.createTrackbar('curcolor','color',0,4,callback)
while True:
index = cv2.getTrackbarPos('curcolor','color')
cvt_img = cv2.cvtColor(img,colorspaces[index])
cv2.imshow('color',cvt_img)
key = cv2.waitKey(10)
if key & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
numpy基本操作
import numpy as np
import cv2
###定义zeros矩阵
# c = np.zeros((8,8),np.uint8)
# print(c)
###定义ones矩阵
###3 3个通道
# d = np.ones((8,8,3),np.uint8)
# print(d)
###定义full矩阵
# e = np.full((8,8),10 ,np.uint8)
# print(e)
###定义单位矩阵identity
# f = np.identity(4)
# print(f)
###eye
# g = np.eye(5,7)
# print(g)
# h = np.eye(5,7,k=3)
# print(h)
####3 通道
img = np.zeros((480,640,3),np.uint8)
###检索值
print(img[100,100])
###向矩阵中某个元素赋值
count = 0
while count <200:
###BGR 改变第二层
img[count,100,1] = 255
###第1层0 第2层0 第3层255
# img[count,100] = [0,0,255]
count = count+1
cv2.imshow('img',img)
key = cv2.waitKey(0)
if key & 0xFF == ord('q'):
cv2.destroyAllWindows()
numpy获取子矩阵
import numpy as np
import cv2
###取一小块
roi = img[100:400,100:600]
roi[:] = [0,0,255]
roi[10:200,10:200] = [0,255,0]
cv2.imshow('img',roi)
key = cv2.waitKey(0)
if key & 0xFF == ord('q'):
cv2.destroyAllWindows()
mat深拷贝
###默认情况下都是浅拷贝,使用copy情况下才是深拷贝
import cv2
import numpy as np
img = cv2.imread("C:\\Users\dazhi\Desktop\-4113ee2870ecf076.jpg")
###浅拷贝
img2 = img
###深拷贝
img3 = img.copy()
img[10:100,10:100] = [0,0,255]
cv2.imshow('img',img)
cv2.imshow('img2',img2)
cv2.imshow('img3',img3)
cv2.waitKey(0)
访问图像的属性
import cv2
import numpy as np
img = cv2.imread("C:\\Users\dazhi\Desktop\-4113ee2870ecf076.jpg")
###shape中包含了三个信息 高度 长度 通道数
print(img.shape)
###计算图像占用多大空间 高度X长度 *通道数
print(img.size)
###图像中每个元素的位深
print(img.dtype)
通道分割与合并
import cv2
import numpy as np
###创建全黑的图片
img = np.zeros((480,640,3),np.uint8)
###分别得到每个通道的值
b,g,r = cv2.split(img)
b[10:100,10:100] = 255
g[10:100,10:100] = 255
###合并图像
#####绿色+蓝色 变成了青色
img2 = cv2.merge((b,g,r))
###显示图像
cv2.imshow('img',img)
cv2.imshow('b',b)
cv2.imshow('g',g)
cv2.imshow('img2',img2)
cv2.waitKey(0)
本文档只是基本入门 目的主要是了解怎么使用,没进行更深了解