学习了图片的加载,显示,基本交互的waitkey,视频的逐帧遍历,颜色通道的基本操作和根据权重合并图片。中途还测试了由charGPT生成的边缘检测代码,并封装简化成了一个函数Edge_Dete()
import cv2
import numpy as np
if 0:
img = cv2.imread('D:\\Myproject\\OPENCV\\picture\\lena.jpg')
cv2.imshow('image',img) #显示图片
cv2.waitKey(0) #等待任意按键退出
if 0:
img = cv2.imread('D:\\Myproject\\OPENCV\\picture\\lena.jpg')
print(img.shape) #打印图片尺寸深度
if 0:
img_gray = cv2.imread('D:\\Myproject\\OPENCV\\picture\\lena.jpg',cv2.IMREAD_GRAYSCALE) #加载灰度图
cv2.imshow('image_gray', img_gray)
cv2.waitKey(0)
#打开视频并逐帧遍历
if 0:
video = cv2.VideoCapture('D:\\Myproject\\OPENCV\\video\\street.mp4')
if video.isOpened():
print('视频打开成功')
else:
open = False
print('视频打开失败')
exit()
while 1:
ret,frame = video.read()
if frame is None:
print('视频结束')
break
else:
cv2.imshow('video',frame)
cv2.waitKey(33)
if 0:
img = cv2.imread('D:\\Myproject\\OPENCV\\picture\\lena.jpg')
cv2.imshow('ROI',img[100:200,100:400]) #设置ROI
cv2.waitKey(0)
#分离三通道数据
green,red,blue = cv2.split(img)
print('green:',green)
print('red:',red)
print('blue:',blue)
#直接设置通道值
if 0:
img = cv2.imread('D:\\Myproject\\OPENCV\\picture\\lena.jpg')
img[:,:,0] = 0 #G通道设置为0
img[:,:,1] = 0 #R通道设置为0
#B通道默认
cv2.imshow('red_only',img)
cv2.waitKey(0)
if 0:
T_size,B_size,L_size,R_size = 50,50,50,50
#边界宽度50
img = cv2.imread('D:\\Myproject\\OPENCV\\picture\\lena.jpg')
#拉伸边缘像素
replicate = cv2.copyMakeBorder(img, T_size, B_size, L_size, R_size, cv2.BORDER_REPLICATE)
cv2.imshow('REPLICATE', replicate)
#镜像
reflect = cv2.copyMakeBorder(img, T_size, B_size, L_size, R_size, cv2.BORDER_REFLECT)
cv2.imshow('REFLECT', reflect)
#除去边缘一行的镜像
reflect_101 = cv2.copyMakeBorder(img, T_size, B_size, L_size, R_size, cv2.BORDER_REFLECT_101)
cv2.imshow('REFLECT_101', reflect_101)
#对边
wrap = cv2.copyMakeBorder(img, T_size, B_size, L_size, R_size, cv2.BORDER_WRAP)
cv2.imshow('WRAP', wrap)
#纯色填充
const = cv2.copyMakeBorder(img, T_size, B_size, L_size, R_size, cv2.BORDER_CONSTANT,value=0xffffff)
cv2.imshow('const', const)
cv2.waitKey(0)
#边缘检测
def Edge_Dete(img, treshold):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, treshold[0], treshold[1])
return edges
if 1:
img = cv2.imread('D:\\Myproject\\OPENCV\\picture\\lena.jpg')
img_edge = Edge_Dete(img, [50, 200])
#重设颜色深度,两张图颜色深度必须相同
img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB)
#重设尺寸,两张图尺寸必须相同
img_edge = cv2.resize(img_edge, [512, 512])
#shape应当是(512, 512, 3)
#print(img_edge.shape)
#根据权重合并图片
img = cv2.addWeighted(img, 0.6, img_edge, 0.8, 0)
cv2.imshow('addweighted', img)
cv2.waitKey(0)
机器视觉是未来智慧城市发展浪潮里不可或缺的一部分,OPENMV,MAIXPY终究局限性较大,想要更加专业OPENCV是必经之路,趁着寒假硬件的进度被拖慢学一学纯软件的东西。