opencv-python基本操作

opencv-python基本操作

            • 需要导入的函数库
            • 读取并显示图像
            • 像素的四则运算:
            • 位运算:
            • 计算均值和方差:
            • 图像模糊:
            • 阈值分割:
            • 形态学操作:
            • 视频的加载与显示
            • 读取图片集合:
            • Canny边缘检测
            • 高斯金字塔
            • 绘制图像
            • 获取视频的属性
            • 读取图片并保存为视频:
            • 对视频进行修改并保存:
            • 将图像分割成多个子图:
            • 提取图像中brisk交点:

需要导入的函数库
import cv2 as cv
import numpy as np
读取并显示图像
src = cv.imread("figure.png")
cv.imshow("figure", src)
cv.waitKey(0)
像素的四则运算:
def calculate(image1, image2):  # 像素的四则运算
    # dst = cv.add(image1,image2)  # 像素相加
    dst = cv.subtract(image1,image2)  # 像素相减
    # dst = cv.multiply(image1, image2)  # 像素相乘
    # dst = cv.divide(image1, image2)  # 像素相除\
    return dst
位运算:
def bitwise(image1, image2):  # 位运算
    dst = cv.bitwise_and(image1, image2)  # 按位进行与运算
    dst = cv.bitwise_or(image1, image2)  # 按位进行或运算
    dst = cv.bitwise_not(image1)  # 按位取反
    dst = cv.bitwise_xor(image1, image2)  # 按位进行异或运算
计算均值和方差:
def mean_dev1(gray):
   M, Dev = cv.meanStdDev(gray)
  	 return M, Dev
图像模糊:
def blur(image):
    # dst = cv.blur(image,(5,5))  #均值模糊
    dst = cv.medianBlur(image,5)  #中值模糊
    # dst = cv.GaussianBlur(src,(5,5),0)  # 高斯模糊
    # dst = cv.bilateralFilter(image, 0, 100, 15)  #双边滤波
    kernel = [[-1,-1,-1,-1,-1],[-1,-1,4,-1,-1,],[-1,4,4,4,-1],[-1,-1,4,-1,-1],[-1,-1,-1,-1,-1]] #设置自定义模糊的卷积核
    dst = cv.filter2D(image, -1, kernel=np.array(kernel, dtype=np.float32))
    cv.imshow("blur image",dst)
    return dst
阈值分割:
def threshold(gray):  # 前提要转为灰度图像
    # ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY|cv.THRESH_OTSU)  # 全局二值化
    # ADAPTIVE_THRESH_MEAN_C 阈值取自相邻区域的平均值
    # ADAPTIVE_THRESH_GAUSSIAN_C 阈值取自相邻区域的加权和,权重为一个高斯窗口
    binary = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 25, 10)  # 局部二值化
    cv.imshow("binary", binary)
    return binary
形态学操作:
def morphology(binary):  # 形态学操作
    kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))  # 获取形态学操作的结构元
    # dst = cv.erode(binary, kernel=kernel)  # 腐蚀操作
    dst = cv.dilate(binary, kernel= kernel)  # 膨胀操作
    # dst = cv.morphologyEx(binary, cv.MORPH_OPEN, kernel= kernel)  # 开操作:先腐蚀后膨胀
    # dst = cv.morphologyEx(binary, cv.MORPH_CLOSE, kernel = kernel)  # 闭操作:先膨胀后腐蚀
    # dst = cv.morphologyEx(binary, cv.MORPH_TOPHAT, kernel= kernel)  # 顶帽操作:原图像 - 开操作
    # dst = cv.morphologyEx(binary, cv.MORPH_BLACKHAT, kernel=kernel)  # 黑帽操作:闭操作 - 原图像
    cv.imshow("morphology image", dst)
    return dst
视频的加载与显示
 def video():  # 视频的加载与显示
    capture = cv.VideoCapture(r"F:\002python\test_video\target_006.avi")
    while(True):
        ret, frame = capture.read()
        print(capture.get(1))
        # frame = cv.flip(frame, 1)
        cv.imshow("video", frame)
        c = cv.waitKey(500)
        if c==27:
            capture.release()
            cv.destroyAllWindows()
            break     
读取图片集合:
def image_set():  # 读取图片集合
    for i in np.arange(1500):
     src = cv.imread(r"F:\002python\data12\data12\\"+str(i)+".bmp")
     cv.imshow("video", src)
     c = cv.waitKey(5)
     if c == 27:
         break
Canny边缘检测
def edge_demo(image):  # Canny边缘检测
    blurred = cv.GaussianBlur(image, (3,3), 0)
    gray = cv.cvtColor(blurred,cv.COLOR_BGR2GRAY)
    xgrad = cv.Sobel(gray,cv.CV_16SC1, 1, 0)
    ygrad = cv.Sobel(gray,cv.CV_16SC1, 0, 1)
    image_output = cv.Canny(xgrad, ygrad, 50, 150)
    cv.imshow("image_output image", image_output)
高斯金字塔
def pyramid(image):  # 高斯金字塔
    Gaussian_pyr = cv.pyrDown(image)  # 获得一层金字塔
    laplace_pyr = image - cv.pyrUp(Gaussian_pyr)
    cv.imshow("gaussian pyramid", Gaussian_pyr)
    cv.imshow("laplace pyramid", laplace_pyr)
绘制图像
绘制直线、矩形、圆形
cv.line(img,(256,0),(256,256),(256,0,0),2)  # b:蓝 g:绿 r:红
cv.rectangle(img,(0,0),(256,256),(256,256,256),2)
cv.circle(img,(256,256),50,(0,0,256),1)
获取视频的属性
# 视频的属性:
print("当前帧在视频中的位置:",capture.get(0), "ms")
print("当前帧在视频中的位置:",capture.get(1), "帧")
print("当前帧在视频中的相对位置:", capture.get(2))
print("视频帧图像的宽度:",capture.get(3),"像素")
print("视频帧图像的高度:",capture.get(4),"像素")
print("帧频:", capture.get(5), "帧/秒")
print("编解码器的四字符代码:",capture.get(6))
print("视频中的总帧数目",capture.get(7), "帧")
print("相机的亮度:",capture.get(10))
print("相机的对比度:",capture.get(11))
print("相机的饱和度:", capture.get(12))
print("相机的色调:",capture.get(13))
print("相机的增益:",capture.get(14))
print("相机的曝光:",capture.get(15))
读取图片并保存为视频:
#将图片集合保存为视频:
fourcc = cv.VideoWriter_fourcc(*'XVID')
out = cv.VideoWriter('target_009.avi', fourcc, 30.0, (256, 256))
for i in range(0, 399):
    frame = cv.imread(r"C:\Users/admin\Downloads\data1\data1/" + str(i) + ".bmp")
    out.write(frame)
    cv.imshow('frame', frame)
    key = cv.waitKey(10)
    if key == 27:
        break
out.release()
cv.destroyAllWindows()
对视频进行修改并保存:
fourcc = cv.VideoWriter_fourcc(*'XVID')
cap = cv.VideoCapture(r"vide.m4s")
ret, frame = cap.read()
heiht, weight = frame.shape[:2]
out = cv.VideoWriter('target_012.avi', fourcc, 30.0, (weight-100, heiht-80))
while True:
    cv.imshow("frame", frame)
    ret, frame = cap.read()

    if int(cap.get(0) >= 30000 and cap.get(0) <= 50000):
        out.write(frame[40:heiht-40, 50:weight-50])
    elif cap.get(1) < 25000:
        pass
    else:
        break
    key = cv.waitKey(1)
    if key == 27:
        break
cap.release()
out.release()
cv.destroyAllWindows()
将图像分割成多个子图:
def divide_img(image, height, width, m, n):  # m表示每行分割多少个,n表示分割多少行
    print('h={},w={},n={},m={}'.format(height, width, n, m))
    dis_h = int(np.floor((height-20) / n))
    dis_w = int(np.floor((width-20) / m))
    num = 0
    for i in range(n):
        for j in range(m):
            num += 1
            print('i,j={},{}'.format(i, j))
            sub = image[dis_h * i:dis_h * (i + 1), dis_w * j:dis_w * (j + 1), :]
            cv2.imshow("sub", sub)
            cv2.waitKey(0)
提取图像中brisk交点:
import cv2
def main():
    img = cv2.imread(r"F:\002python\dataset_own\images\others\girl1.jpg")
    cv2.imshow('Input Image', img)
    brisk = cv2.BRISK_create()
    kp, des = brisk.detectAndCompute(img, None)
    img2 = img.copy()
    img2 = cv2.drawKeypoints(img, kp, img2, color=(0, 255, 0))
    cv2.imshow('Detected BRISK keypoints', img2)
    cv2.waitKey(0)

你可能感兴趣的:(杂文,opencv,cv,计算机视觉,python,图像识别)