opencv 不支持透明
R G B 设备独立空间 1.图像读取与显示def red_deno():
image = cv.imread("D:/0.jpg") #注意符号
cv.imshow("input",image)
cv.waitKey(0)
cv.destroyAllWindows()
2.图像色彩空间转换
def color_space_demo(): #色彩空间
image = cv.imread("D:/0.jpg") # 注意符号 rgb,0-255
gray = cv.cvtColor(image,cv.COLOR_RGB2GRAY) #处理为灰度
hsv = cv.cvtColor(image,cv.COLOR_RGB2HSV) #处理hsv H 0 0-180 cv.imshow("gray",gray)
cv.imshow("hsv",hsv)
cv.waitKey(0)
cv.destroyAllWindows()
3.图像对象的创建与读写
def mat_demo(): #色彩空间
image = cv.imread("D:/0.jpg") # 注意符号 rgb,0-255
print(image.shape) #(417, 500, 3) 高,宽,通道数
print(image) #图片就是一串数组
roi = image[60:100,60:200,:] #创建一个空白区域
blank = np.zeros_like(image) # blank[60:100,60:200] = image[60:100,60:200] #截取一个图片空间
blank = image #blank = np.copy(image) #直接原图拷贝过来
cv.imshow("image",image)
cv.imshow("blank", blank)
cv.imshow("roi", roi)
cv.waitKey(0)
cv.destroyAllWindows()
4.图片像素的读写操作
def pixel_demo(): #色彩空间
image = cv.imread("D:/0.jpg") # 注意符号 rgb,0-255
cv.imshow("input", image) #显示输入图片
h,w,c = image.shape
for row in range (h):
for col in range (w):
r,g,b=image[row,col]
image[row,col] = r-255,g-255,b-255 #rgb取反
cv.imshow("result",image)
cv.imwrite("D:/result.png",image) #将输出后图片进行保留
cv.waitKey(0)
cv.destroyAllWindows()
5.图像像素的算数操作
def math_demo(): #色彩空间
image = cv.imread("D:/0.jpg") # 注意符号 rgb,0-255
cv.imshow("input", image) #显示输入图片
h,w,c = image.shape
blank = np.zeros_like(image)
blank[:,:] = (8,8,8)
cv.imshow("blank",blank)
# result = cv.add(image,blank) #增加对比度,加法运算
result = cv.subtract(image, blank) #减法运算
result = cv.divide(image, blank) #除法运算
result = cv.multiply(image, blank) #乘法运算
cv.imshow("result",result)
cv.waitKey(0)
cv.destroyAllWindows()
6.TrackBar/滚动条操作演示-调整图像亮度
def nothing(x):
print(x)
def adjust_light_demo():
image = cv.imread("D:/0.jpg") # 注意符号 rgb,0-255
cv.namedWindow("input", cv.WINDOW_AUTOSIZE) cv.createTrackbar("light","input",0,100,nothing)
cv.imshow("input",image)
blank = np.zeros_like(image)
while True:
pos = cv.getTrackbarPos("light","input")
blank[:,:] = (pos,pos,pos)
# cv.imshow("blank",blank)
# result = cv.add(image,blank) #增加对比度,加法运算
result = cv.subtract(image, blank) #减法运算
# result = cv.divide(image, blank) #除法运算
# result = cv.multiply(image, blank) #乘法运算
cv.imshow("result",result)
c=cv.waitKey(1)
if c == 27:
break
cv.destroyAllWindows()
7.TrackBar/滚动条操作演示-参数传递与调整亮度与对比度
def adjust_contrst_demo():
image = cv.imread("D:/0.jpg") # 注意符号 rgb,0-255
cv.namedWindow("input", cv.WINDOW_AUTOSIZE) cv.createTrackbar("light","input",0,100,nothing)
cv.createTrackbar("contrst", "input", 100, 200, nothing)
cv.imshow("input",image)
blank = np.zeros_like(image)
while True:
light = cv.getTrackbarPos("light","input")
contrst = cv.getTrackbarPos("contrst", "input")/100 print("light",light,"contrst",contrst)
# blank[:,:] = (light,light,light)
result = cv.addWeighted(image,contrst,blank,0.5,light)
cv.imshow("result",result)
c=cv.waitKey(1)
if c == 27:
break
cv.destroyAllWindows()
8.键盘响应操作
def keny_demo(): #键盘响应
image = cv.imread("D:/0.jpg") # 注意符号 rgb,0-255
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input",image)
while True:
c = cv.waitKey(1) #停顿一毫秒
if c ==49: #1
gray = cv.cvtColor(image,cv.COLOR_RGB2GRAY)
cv.imshow("result",gray)
if c == 50: #2
hsv = cv.cvtColor(image,cv.COLOR_RGB2HSV)
cv.imshow("result", hsv)
if c == 51: #3
invert = cv.bitwise_not(image)
cv.imshow("result", invert)
# if c == 52:
# invert = cv.bitwise_and(image)
# cv.imshow("result", invert)
if c == 27:
break
cv.destroyAllWindows()
9.opencv自带颜色表操作
def color_table_demo(): #键盘响应
colormap = [ cv.COLORMAP_AUTUMN,
cv.COLORMAP_BONE,
cv.COLORMAP_JET,
cv.COLORMAP_WINTER,
cv.COLORMAP_RAINBOW,
cv.COLORMAP_OCEAN,
cv.COLORMAP_SUMMER,
cv.COLORMAP_SPRING,
cv.COLORMAP_COOL,
cv.COLORMAP_HSV,
cv.COLORMAP_PINK,
cv.COLORMAP_HOT]
image = cv.imread("D:/0.jpg") # 注意符号 rgb,0-255
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input",image)
index = 0
while True:
dst = cv.applyColorMap(image,colormap[index%12]) #取模12
index += 1
cv.imshow("color style",dst)
c = cv.waitKey(1000) # 停顿一毫秒
if c == 27:
break
cv.destroyAllWindows()

10.图像像素的逻辑操作
def bitwise_demo():
b1 = np.zeros((400,500,3),dtype = np.uint8)
b1[:,:] = (0,255,0)
b2 = np.zeros((400, 500,3), dtype=np.uint8)
b2[:, :] = (255,0,255) cv.imshow("b1", b1)
cv.imshow("b2", b2)
dst1 = cv.bitwise_and(b1,b2)
dst2 = cv.bitwise_or(b1,b2)
dst3 = cv.bitwise_not(b1,b2)
cv.imshow("bitwise_and", dst1)
cv.imshow("bitwise_or", dst2)
cv.imshow("bitwise_not", dst3)
cv.waitKey(0)
cv.destroyAllWindows()
11.通道分离与合并
def channels_split_demo():
b1 = cv.imread("D:/0.jpg")
print(b1.shape)
cv.imshow("input", b1)
cv.imshow("b2", b1[:,:,-1]) #[:,:,-1]和[:,:,3] 倒数第一和正数第三
mv = cv.split(b1) #分离
mv[0][:,:] = 255
result = cv.merge(mv) #合并
cv.imshow("result",result)
print(len(mv))
cv.waitKey(0)
cv.destroyAllWindows()
12.图像色彩空间转换
def color_space_demo():
b1 = cv.imread("D:/245.jpg")
print(b1.shape)
cv.imshow("input", b1)
hsv = cv.cvtColor(b1,cv.COLOR_RGB2HSV)
cv.imshow("hsv",hsv)
mask = cv.inRange(hsv,(35,43,46),(77,255,255))
cv.bitwise_not(mask,mask)
result = cv.bitwise_and(b1,b1,mask=mask)
cv.imshow("result",result)
cv.waitKey(0)
cv.destroyAllWindows()
hsv过滤表
13.图像的像素统计def pixel_means_demo():
b1 = cv.imread("D:/245.jpg")
print(b1.shape)
cv.imshow("input", b1)
print(np.max(b1[:,:,2]))
means,dev = cv.meanStdDev(b1)
print(means,"dev",dev)
cv.waitKey(0)
cv.destroyAllWindows()
结果为像素 ,通道数
最大值
r g b 三个均值
r g b 三个方差
14.图像几何形状绘制def dawing_demo():
# b1 = np.zeros((512,512,3),dtype = np.uint8)
b1 = cv.imread("D:/245.jpg")
b2 = np.copy(b1)
cv.rectangle(b1,(50,50),(400,400),(0,0,255),4,8,0) #绘制矩形
# cv.circle(b1,(200,200),100,(255,2,255),-1,8,0) #绘制圆形
# cv.line(b1,(50,50),(400,400),(0,0,255),4,8,0) #绘制直线
cv.putText(b1,"99%face",(50,50),cv.FONT_HERSHEY_SIMPLEX,1.0,(0,255,254),2,8,0)
# b1[:,:,:] = 0 #清除绘图痕迹
# b1 = b2 #方法二 先复制一个空白图再调用
cv.imshow("result",b1)
# b1 = cv.imread("D:/245.jpg")
cv.waitKey(0)
cv.destroyAllWindows()
15.随机数和随机颜色
def random_color_demo():
b1 = np.zeros((512,512,3),dtype = np.uint8)
while True:
xx = np.random.randint(0,512,2,dtype = np.int)
yy = np.random.randint(0,512,2,dtype = np.int)
bgr = np.random.randint(0,255,3,dtype = np.int32) print(bgr[0],bgr[1],bgr[2],xx[0],yy[0],xx[1],yy[1])
cv.line(b1,(xx[0],yy[0]),(xx[1],yy[1]),(np.int(bgr[0]),np.int(bgr[1]),np.int(bgr[2])),8,8,0) #绘制直线
cv.imshow("result",b1)
c = cv.waitKey()
if c == 27:
break
cv.destroyAllWindows()
16.多边形填充与绘制
def polyline_drawing_demo():
canvas = np.zeros((512,512,3),dtype = np.uint8)
pts = np.array([[100,100],[350,100],[450,280],[320,320],[80,400]],dtype=np.int32) #这是一个数组 cv.fillPoly(canvas,[pts],(255,0,0),8,0) #填充
cv.polylines(canvas,[pts],True,(0,255,0),2,8,0) #绘制外框
# cv.drawContours(canvas,[pts],-1,(255,0,0),-1) #填充加绘制
cv.imshow("result", canvas)
cv.waitKey(0)
cv.destroyAllWindows()
17.鼠标操作与响应
b1 = cv.imread("D:/245.jpg") #np.zeros((512,512,3),dtype = np.uint8)
b2 = np.copy(b1)
x1 = -1
x2 = -1
y1 = -1
y2 = -1
def mouse_drawing(event,x,y,flags,param):
global x1,y1,x2,y2
if event == cv.EVENT_LBUTTONDOWN:
x1 = x
y1 = y
if event == cv.EVENT_MOUSEMOVE:
if x1<0 or y1<0:
return
x2 = x
y2 = y
dx = x2 - x1
dy = y2 - y1
if dx > 0 and dy > 0:
b1[:,:,:] = b2
cv.rectangle(b1,(x1,y1),(x2,y2),(0,255,0),2,8,0)
if event == cv.EVENT_LBUTTONUP:
if x1<0 or y1<0:
return
x2 = x
y2 = y
dx = x2 - x1
dy = y2 - y1
if dx > 0 and dy > 0:
b1[:,:,:] = b2
cv.rectangle(b1,(x1,y1),(x2,y2),(0,255,0),2,8,0)
x1 = -1
x2 = -1
y1 = -1
y2 = -1
def mouse_demo():
cv.namedWindow("mouse_demo",cv.WINDOW_AUTOSIZE)
cv.setMouseCallback("mouse_demo",mouse_drawing)
while True:
cv.imshow("mouse_demo", b1)
c = cv.waitKey(10)
if c == 27:
break
cv.destroyAllWindows()
18.图像像素类型转换与归一化
def norm_demo():
image = cv.imread("D:/245.jpg")
cv.namedWindow("mouse_demo",cv.WINDOW_AUTOSIZE)
result = np.zeros_like(np.float32(image)) cv.normalize(np.float32(image),result,0,1,cv.NORM_MINMAX,dtype=cv.CV_32F)
cv.imshow("mouse_demo", np.uint8(image*255))
# print(image/255)
c = cv.waitKey(0)
cv.destroyAllWindows()
19.图像放缩与插值
def resize_demo():
image = cv.imread("D:/245.jpg")
h, w, c = image.shape
cv.namedWindow("resize_demo",cv.WINDOW_AUTOSIZE)
# dst = cv.resize(image,(w//2,h//2),interpolation=cv.INTER_BITS2) #只能对整数操作
dst = cv.resize(image, (0,0),fx = 0.75,fy=0.75, interpolation=cv.INTER_BITS2) #可对任意大小操作 cv.imshow("resize_demo()",dst)
c = cv.waitKey(0)
cv.destroyAllWindows()
20.图像翻转
def flip_demo():
image = cv.imread("D:/245.jpg")
cv.imshow("input", image)
cv.namedWindow("resize_demo",cv.WINDOW_AUTOSIZE)
dst = cv.flip(image,-1)
cv.imshow("flip_demo()",dst)
c = cv.waitKey(0)
cv.destroyAllWindows()
21.图像旋转
def rotate_demo():
src = cv.imread("D:/245.jpg")
cv.imshow("input", src)
h, w, c = src.shape
# 定义矩阵
M = np.zeros(( 2, 3), dtype=np.float32)
# 定义角度
alpha = np.cos(np.pi / 4.0)
beta = np.sin(np.pi / 4.0)
print( "alpha : ", alpha)
# 初始化矩阵
M[ 0, 0] = alpha
M[ 1, 1] = alpha
M[ 0, 1] = beta
M[ 1, 0] = -beta
cx = w / 2
cy = h / 2
tx = ( 1-alpha)*cx - beta*cy
ty = beta*cx + ( 1-alpha)*cy
M[ 0, 2] = tx
M[ 1, 2] = ty
# change with full size
bound_w = int(h * np.abs(beta) + w * np.abs(alpha))
bound_h = int(h * np.abs(alpha) + w * np.abs(beta))
# 添加中心位置迁移
M[ 0, 2] += bound_w / 2- cx
M[ 1, 2] += bound_h / 2- cy
dst = cv.warpAffine(src, M, (bound_w, bound_h))
cv.imshow( "rotate without cropping", dst)
c = cv.waitKey(0)
cv.destroyAllWindows()
22.视频文件和摄像头使用
def video_demo():
cap = cv.VideoCapture(0) #读取摄像头编号为0
# cap = cv.VideoCapture("C:/Users/asus/哈哈哈哈.mp4")
w = cap.get(cv.CAP_PROP_frame_WIDTH)
h = cap.get(cv.CAP_PROP_frame_HEIGHT)
fps = cap.get(cv.CAP_PROP_FPS)
print(w, h, fps)
while True:
ret ,frame = cap.read()
frame = cv.flip(frame,1) #读取视频时可不用
if ret is not True:
break
cv.imshow("frame",frame)
c = cv.waitKey(10)
if c == 27:
break
cv.destroyAllWindows()
23.视频处理与保存
def video_demo(): cap = cv.VideoCapture("C:/Users/asus/哈哈哈哈.mp4")
w = cap.get(cv.CAP_PROP_frame_WIDTH)
h = cap.get(cv.CAP_PROP_frame_HEIGHT)
fps = cap.get(cv.CAP_PROP_FPS)
out = cv.VideoWriter("D:TEST.mp4",cv.VideoWriter.fourcc('P','I','M','1'),fps(np.int(w),np.int(h)),True) print(w, h, fps)
while True:
ret ,frame = cap.read()
frame = cv.flip(frame,1) #读取视频时可不用
if ret is not True:
break
cv.imshow("frame",frame)
c = cv.waitKey(10)
if c == 27:
break
cv.destroyAllWindows()
out.release()
24.图像直方图
def image_hist():
image = cv.imread("D:/245.jpg")
cv.imshow( "input", image)
color = ('blue','green','red')
for i,color in enumerate(color):
hist = cv.calcHist([image],[i],None,[256],[0,256])
print(hist)
plt.plot(hist,color = color)
plt.xlim(0,256)
plt.show()
cv.waitKey(0)
cv.destroyAllWindows()
25.二维直方图
def image_hist2d():
image = cv.imread("D:/245.jpg")
hsv = cv.cvtColor(image,cv.COLOR_RGB2HSV)
hist = cv.calcHist([hsv], [0,1], None, [64,64], [0,180,0, 256])
dst = cv.resize(hist,(800,800))
cv.normalize(dst,dst,0,255,cv.NORM_MINMAX)
cv.imshow( "input", image)
dst = cv.applyColorMap(np.uint8(dst),cv.COLORMAP_JET)
cv.imshow("hist", dst)
plt.imshow(hist,interpolation='nearest')
plt.title('2D Histogram')
plt.show()
cv.waitKey(0)
cv.destroyAllWindows()
26.直方图均衡化
def equal_hist2d():
image = cv.imread("D:/245.jpg",cv.IMREAD_GRAYSCALE)
cv.imshow("input",image)
result = cv.equalizeHist(image)
cv.imshow("result",result)
cv.waitKey(0)
cv.destroyAllWindows()
27.图像卷积操作
均值卷积和高斯卷积(权重系数不同)
def conv_demo():
image = cv.imread("D:/245.jpg")
cv.imshow("input",image)
result = cv.blur(image,(5,5))
cv.imshow("result",result)
cv.waitKey(0)
cv.destroyAllWindows()
28.高斯模糊
def GaussianBlur_demo():
image = cv.imread("D:/245.jpg")
cv.imshow("input",image)
result = cv.GaussianBlur(image,(3,3),5) #必须为奇数
cv.imshow("result",result)
cv.waitKey(0)
cv.destroyAllWindows()
29.高斯双边模糊
def bifilter_demo():
image = cv.imread("D:/012.png")
cv.imshow("input",image)
result = cv.bilateralFilter(image,0,100,10)
cv.imshow("result",result)
cv.waitKey(0)
cv.destroyAllWindows()



