1.加载图片或者视频
import cv2
#path:文件路径:加载文件
def show_image(path)
image = cv2.imread(path)
#创建窗口
cv2.namedWindow('image',cv2.WINDOW_AUTOSIZE)
cv2.imshow(image)
cv2.waitKey(40)
cv2.destoryallwindow()
#加载视频
def show_vedio_demo(path):
#path如果为0,显示调用自身摄像头
capture = cv2.VideoCapture(path)
ret,frame = capture.read()
if ret==False:
break
cv2.imshow('vedio',frame)
cv = cv2.waitkey(40)
#27:Esc
if cv == 27:
break
2.图像信息
def get_image_info(image):
print('type:',type(image))
#像素信息:height,width,channels
#长、高、通道数:色彩通道:0:BLUE 1:GREEN 2.RED
print('shape:',image.shape)
#size = 长*高*通道数
print('size:',image.size)
#image.dtype:像素类型
print('dtype:',image.dtype)
3.生成图像:利用numpy
import cv2
import numpy as np
img = np.ones([400,400,3],dtype=np.uint8)
img = img * 125
cv2.imshow(img)
cv2.waitKey(10)
cv2.destoryallwindow()
#测试0:BLUE 1:GREEN 2.RED
def get_image():
img = np.zeros([400,400,3],dtype=np.uint8)
#通道0
#img[:,:,0] = np.ones([400,400],dtype = np.uint8)*100
#通道1
#img[:,:,1] = np.ones([400,400],dtype = np.uint8)*100
#通道2
#img[:,:,1] = np.ones([400,400],dtype = np.uint8)*100
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destorallwindow()
4.像素转换
def pixel_info(image):
shape = image.shape
height = shape[0]
width = shape[1]
channels = shape[2]
for row in range(height):
for col in range(width):
for channel in range(channels):
pixel = image[row,col,channel]
image[row,col,channel] = 255-pixel
return image
#测试时间:速度慢
#用于返回CPU的频率:getTickFrequency()
frequence = cv2.getTickFrequency()
t1 = cv2.getTickCount()
image = pixel_info(image)
t2 = cv2.getTickCount()
print((t2-t1)/frequence)
#自带API:速度快
def inverse_pixel(image):
image = cv2.bitwise_not(image)
#写入文件
cv2.imwrite('inverse_image',image)
return image
5.色彩空间转换
#常见色彩空间:RGB
def change_color_space(image,space_type):
#RGB转为其它类型,此处暂时列了rgb转为:hsv,hls,yuv
if space_type = 'HSV':
image_new = cv2.cvtColor(image,cv2.COLOR_RGB2HSV)
if space_type = 'HLS'
image_new = cv2.cvtColor(image,cv2.COLOR_RGB2HLS)
if space_type = 'YUV':
image_new = cv2.cvtColor(image,cv2.COLOR_RGB2YUV)
return image_new
#inRange方法#二值化功能
#提取某个颜色
#inRange(src, lowerb, upperb[, dst]) -> dst
def extract_from_video(path):
capture = cv2.VideoCapture(path)
ret,frame = capture.read()
#lowerd,upperb:随机定义的
if ret==False:
break
lowerd = np.array([10,45,56])
upperb = np.array([20,255,255])
frame = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
frame = cv2.inRange(frame,lowerd=lowerd,upperb=upperb)
cv2.imshow('vedio',frame)
cv = cv2.waitKey(50)
if cv == 27:
break
6.通道分割/合并
def split_image(image):
b,g,r = cv2.split(image)
cv2.imshow('blue',b)
cv2.imshow('green',g)
cv2.imshow('red',r)
cv2.waitKey(0)
cv2.destorallwindow()
def merge_image():
image = cv2.merge([b,g,r])
return image