c++获取图像的长宽 opencv_yi点分享 | opencv+python 常用方法汇总(持续更新)

c++获取图像的长宽 opencv_yi点分享 | opencv+python 常用方法汇总(持续更新)_第1张图片
  1. 图像的输入、输出
  2. 获取图像基本信息
  3. 像素取反
  4. 色彩空间转换
  5. 捕捉视频中的颜色物块
  6. 通道的分离与合并
  7. 算术运算
  8. 逻辑运算
  9. 调整图像亮度、对比度
  10. 泛洪填充
  11. 模糊操作
  12. 高斯噪声、高斯模糊
  13. 边缘保留滤波(EPF)
  14. 像素直方图
  15. 像素直方图应用
  16. 直方图反向投影(定位)
  17. 模板匹配
  18. 图像二值化
  19. 图像金字塔
  20. 图像梯度
  21. Canny边缘提取
  22. 直线检测
  23. 提取水平、竖直线
  24. 圆检测
  25. 轮廓发现
  26. 对象测量
  27. 膨胀、腐蚀
  28. 开闭操作
  29. 其他形态学操作
  30. 分水岭算法(图像分割)
  31. 人脸检测
  32. 数字验证码识别

01、输入、输出

读取图像

src = cv.imread("E:/opencv/OPENCV_3.1/opencv/sources/samples/data/test.jpg")

显示图像

cv.imshow("input image", src)

保存图像

cv.imwrite("C:/Users/ASUS/Desktop/test1.jpg", gray)

从摄像头读进视频

def video_demo():  # opencv 读进来的视频无声音
    capture = cv.VideoCapture(0)  # 第0个摄像头
    while True:
        ret, frame = capture.read()
        frame = cv.flip(frame, 1)  # 1上下颠倒 0左右颠倒 -1都颠倒
        cv.imshow("video", frame)
        c = cv.waitKey(50)
        if c == 27:
            break

02、获取图像基本信息

def get_image_info(image):
    print(type(image))
    print(image.shape)
    print(image.size)
    print(image.dtype)
    pixel_data = np.array(image)
    print(pixel_data)

03、像素取反

# 自己写的方法
def access_pixels(image):
    print(image.shape)
    height = image.shape[0]
    width = image.shape[1]
    channels = image.shape[2]
    print("width: %s, height: %s, channels: %s" % (width, height, channels))
    for row in range(height):
        for col in range(width):
            for c in range(channels):
                pv = image[row, col, c]
                image[row, col, c] = 255 - pv
    cv.imshow("pixels_demo", image)

# opencv 的API
def inverse(img):
    dst = cv.bitwise_not(img)
    cv.imshow("inverse_demo", dst)

04、色彩空间转换

def color_space_demo(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    cv.imshow("gray", gray)
    hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV)
    cv.imshow("hsv", hsv)
    yuv = cv.cvtColor(image, cv.COLOR_BGR2YUV)
    cv.imshow("yuv", yuv)
    ycrcb = cv.cvtColor(image, cv.COLOR_BGR2YCrCb)
    cv.imshow("ycrcb", ycrcb)

05、捕捉视频中的颜色物块

c++获取图像的长宽 opencv_yi点分享 | opencv+python 常用方法汇总(持续更新)_第2张图片
def extrace_object_demo():
    capture = cv.VideoCapture("E:/opencv/OPENCV_3.1/opencv/sources/samples/data/1.mp4")
    while True:
        ret, frame = capture.read()
        if not ret:
            break
        hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
        lower_hsv = np.array([0, 43, 46])
        upper_hsv = np.array([10, 255, 255])
        mask = cv.inRange(hsv, lowerb=lower_hsv, upperb=upper_hsv)
        dst = cv.bitwise_and(frame, frame, mask=mask)
        cv.imshow("dst", dst)
        cv.imshow("video", frame)
        cv.imshow("mask", mask)
        c = cv.waitKey(40)
        if c == 27:
            break

06、通道的分离与合并

src = cv.imread("E:/opencv/OPENCV_3.1/opencv/sources/samples/data/mua.jpg")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)

b, g, r = cv.split(src)  # 分离
cv.imshow("blue", b)
cv.imshow("green", g)
cv.imshow("red", r)

src[:, :, 2] = 0
src1 = cv.merge([b, g, r])  # 合并
cv.imshow("changed image", src)
cv.imshow("changed image1", src1)

07、算术运算

def add_demo(m1, m2):
    dst = cv.add(m1, m2)
    cv.imshow("add_demo", dst)

def subtract_demo(m1, m2):
    dst = cv.subtract(m1, m2)
    cv.imshow("subtract_demo", dst)

def divide_demo(m1, m2):
    dst = cv.divide(m1, m2)
    cv.imshow("divide_demo", dst)

def multiply_demo(m1, m2):
    dst = cv.multiply(m1, m2)
    cv.imshow("multiply_demo", dst)

均值、方差

def others(m1, m2):
    M1, dev1 = cv.meanStdDev(m1) 
    M2, dev2 = cv.meanStdDev(m2)
    print(M1)
    print(M2)
    print(dev1)
    print(dev2)

08、逻辑运算

def logic_demo(m1, m2):
    # dst = cv.bitwise_and(m1, m2)  # 与
    # dst = cv.bitwise_or(m1, m2)  # 或
    dst = cv.bitwise_not(m2)  # 非

    cv.imshow("logic_demo", dst)

09、调整图像亮度、对比度

def contrast_brightness_demo(image, c, b):
    h, w, ch = image.shape
    blank = np.zeros([h, w, ch], image.dtype)
    dst = cv.addWeighted(image, c, blank, 1-c, b)
    cv.imshow("contrast_brightness_demo", dst)

10、泛洪填充

彩色图像泛洪填充

def fill_color_demo(image):
    copyImg = image.copy()
    h, w = image.shape[:2]
    mask = np.zeros([h+2, w+2], np.uint8)
    cv.floodFill(copyImg, mask, (125, 300), (0, 255, 255), (100, 100, 100), (50, 50, 50), cv.FLOODFILL_FIXED_RANGE)
    cv.imshow("fill_color_demo", copyImg)

二值图像泛洪填充

def fill_binary_demo():
    image = np.zeros([400, 400, 3], np.uint8)
    image[100:300, 100:300, :] = 255
    cv.imshow("fill_binary_0", image)

    h, w = image.shape[:2]
    mask = np.ones([h + 2, w + 2, 1], np.uint8)
    mask[101:301, 101:301] = 0

    cv.floodFill(image, mask, (200, 200), (0, 0, 255), cv.FLOODFILL_MASK_ONLY)
    cv.imshow("fill_binary_1", image)

11、模糊操作

均值模糊

def blur_demo(image):
    dst = cv.blur(image, (10, 10))
    cv.imshow("blur_demo", dst)

中值模糊

def median_blur_demo(image):  # 除椒盐噪声
    dst = cv.medianBlur(image, 5)
    cv.imshow("median_blur_demo", dst)

自定义模糊

def custom_blur_demo(image):
    kernel = np.ones([5, 5], np.float32) / 25  # 必须是奇数
    kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], np.float32)  # 总和为一就不用除(锐化)
    dst = cv.filter2D(image, -1, kernel=kernel)
    cv.imshow("custom_blur_demo", dst)

12、高斯噪声、高斯模糊

高斯噪声

def clamp(pv):
    if pv > 255:
        return 255
    elif pv < 0:
        return 0
    else:
        return pv

# 高斯噪声
def gaussian_noise(image):
    h, w, c = image.shape
    for row in range(h):
        for col in range(w):
            s = np.random.normal(0, 20, 3)
            b = image[row, col, 0]
            g = image[row, col, 1]
            r = image[row, col, 2]
            image[row, col, 0] = clamp(b + s[0])
            image[row, col, 1] = clamp(g + s[1])
            image[row, col, 2] = clamp(r + s[2])
    cv.imshow("noise_image", image)

高斯模糊

dst = cv.GaussianBlur(src, (0, 0), 15)

13、边缘保留滤波(EPF)

高斯双边模糊

def bi_demo(image):
    dst = cv.bilateralFilter(image, 0, 100, 15)
    cv.imshow("bi_demo", dst)

均值迁移

def shift_demo(image):
    dst = cv.pyrMeanShiftFiltering(image, 10, 50)
    cv.imshow("shift_demo", dst)

14、像素直方图

# 直方图
def plot_demo(image):
    plt.hist(image.ravel(), 256, [0, 256])
    plt.show()

# 三通道直方图
def image_hist(image):
    color = ('blue', 'green', 'red')
    for i,color in enumerate(color):
        hist = cv.calcHist([image], [i], None, [256], [0, 256])
        plt.plot(hist, color=color)
        plt.xlim([0, 256])
    plt.show()

15、像素直方图应用

全局直方图均衡化

def equalHist_demo(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    dst = cv.equalizeHist(gray)
    cv.imshow("equalHist_demo", dst)

局部自适应直方图均衡化

def clahe_demo(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    clahe = cv.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
    dst = clahe.apply(gray)
    cv.imshow("clahe_demo", dst)

建立RGB三通道直方图

def create_rgb_hist(image):
    h, w, c = image.shape
    rgbHist = np.zeros([16*16*16, 1], np.float32)
    bsize = 256 / 16
    for row in range(h):
        for col in range(w):
            b = image[row, col, 0]
            g = image[row, col, 1]
            r = image[row, col, 2]
            index = np.int(b/bsize)*16*16 + np.int(g/bsize)*16 + np.int(r/bsize)
            rgbHist[np.int(index), 0] = rgbHist[np.int(index), 0] + 1
    return rgbHist

基于直方图的相似度比较

def hist_compare(image1, image2):
    hist1 = create_rgb_hist(image1)
    hist2 = create_rgb_hist(image2)
    match1 = cv.compareHist(hist1, hist2, cv.HISTCMP_BHATTACHARYYA)
    match2 = cv.compareHist(hist1, hist2, cv.HISTCMP_CORREL)
    match3 = cv.compareHist(hist1, hist2, cv.HISTCMP_CHISQR)
    print("巴氏距离:%s  相关性:%s  卡方:%s  "%(match1, match2, match3))

16、直方图反向投影(定位)

建立2D直方图

def hist2d_demo(image):
    hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV)
    hist = cv.calcHist([image], [0, 1], None, [180, 256], [0, 180, 0, 256])
    plt.imshow(hist, interpolation="nearest")
    plt.title("hist2d_demo")
    plt.show()

直方图反向影射

def back_projection_demo():
    target = cv.imread("E:/opencv/OPENCV_3.1/opencv/sources/samples/data/aloeL.jpg")
    sample = cv.imread("E:/opencv/OPENCV_3.1/opencv/sources/samples/data/2.jpg")
    roi_hsv = cv.cvtColor(sample, cv.COLOR_BGR2HSV)
    tar_hsv = cv.cvtColor(target, cv.COLOR_BGR2HSV)

    roiHist = cv.calcHist([roi_hsv], [0, 1], None, [32, 32], [0, 180, 0, 256])
    cv.normalize(roiHist, roiHist, 0, 255, cv.NORM_MINMAX)
    dst = cv.calcBackProject([tar_hsv], [0, 1], roiHist, [0, 180, 0, 256], 1)
    cv.imshow("back_projection_demo", dst)

17、模板匹配

详见我的另一篇文章。

18、图像二值化

全局二值化

def threshold_demo(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
    # ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_TRIANGLE)
    # ret, binary = cv.threshold(gray, 127, 255, cv.THRESH_BINARY)
    # ret, binary = cv.threshold(gray, 127, 255, cv.THRESH_BINARY_INV)
    # ret, binary = cv.threshold(gray, 150, 255, cv.THRESH_TRUNC)
    # ret, binary = cv.threshold(gray, 127, 255, cv.THRESH_TOZERO)
    print("threshold value %s" % ret)
    cv.imshow("binary", binary)

局部二值化

def local_threshold(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    # binary = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 25, 10)
    binary = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 25, 10)
    # cv.imwrite("C:/Users/ASUS/Desktop/mua1.jpg", binary)
    cv.imshow("binary", binary)

自定义二值化

def custom_threshold(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    h, w = gray.shape[:2]
    m = np.reshape(gray, [1,w*h])
    mean = m.sum() / (w*h)
    print("mean:", mean)
    ret, binary = cv.threshold(gray, mean, 255, cv.THRESH_BINARY)
    cv.imshow("binary", binary)

超大图像二值化

def big_image_binary(image):
    print(image.shape)
    cw = 256
    ch = 256
    h, w = image.shape[:2]
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    for row in range(0, h, ch):
        for col in range(0, w, cw):
            roi = gray[row:row+ch, col:col+cw]
            dst = cv.adaptiveThreshold(roi, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 127, 20)
            gray[row:row+ch, col:col+cw] = dst
            print(np.std(dst), np.mean(dst))
    cv.imshow("binary", gray)

19、图像金字塔

高斯金字塔

def pyramid_demo(image):
    level = 3
    temp = image.copy()
    pyramid_images = []
    for i in range(level):
        dst = cv.pyrDown(temp)
        pyramid_images.append(dst)
        cv.imshow("pyramid_down"+str(i), dst)
        temp = dst.copy()
    return pyramid_images

拉普拉斯金字塔

def lapalian_demo(image):
    pyramid_images = pyramid_demo(image)
    level = len(pyramid_images)
    for i in range(level-1, -1, -1):
        if i-1 < 0:
            expand = cv.pyrUp(pyramid_images[i], image.shape[:-2])
            lpls = cv.subtract(image, expand)
            cv.imshow("lapalian_down" + str(i), lpls)
        else:
            expand = cv.pyrUp(pyramid_images[i], pyramid_images[i-1].shape[:-2])
            lpls = cv.subtract(pyramid_images[i-1], expand)
            cv.imshow("lapalian_down"+str(i), lpls)

20、图像梯度

拉普拉斯算子

def lapalian_demo(image):
    dst = cv.Laplacian(image, cv.CV_32F)
    lpls = cv.convertScaleAbs(dst)
    cv.imshow("lapalian_demo", lpls)

Sobel 算子

def sobel_demo(image):
    grad_x = cv.Sobel(image, cv.CV_32F, 1, 0)
    grad_y = cv.Sobel(image, cv.CV_32F, 0, 1)

    gradx = cv.convertScaleAbs(grad_x)
    grady = cv.convertScaleAbs(grad_y)
    # cv.imshow("gradient-x", gradx)
    # cv.imshow("gradient-y", grady)
    gradxy = cv.addWeighted(gradx, 0.5, grady, 0.5, 0)
    cv.imshow("gradient-xy", gradxy)

拉普拉斯算子(自定义)

def lapalian_demo(image):
    kernel = np.array([[1, 1, 1], [1, -8, 1], [1, 1, 1]])
    dst = cv.filter2D(image, cv.CV_32F, kernel=kernel)
    lpls = cv.convertScaleAbs(dst)
    cv.imshow("lapalian_demo", lpls)

Sobel 算子(自定义)

def sobel_demo(image):
    grad_x = cv.Scharr(image, cv.CV_32F, 1, 0)
    grad_y = cv.Scharr(image, cv.CV_32F, 0, 1)

    gradx = cv.convertScaleAbs(grad_x)
    grady = cv.convertScaleAbs(grad_y)
    # cv.imshow("gradient-x", gradx)
    # cv.imshow("gradient-y", grady)
    gradxy = cv.addWeighted(gradx, 0.5, grady, 0.5, 0)
    cv.imshow("gradient-xy", gradxy)

21、Canny边缘提取

def edge_demo(image):
    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)

    edge_output = cv.Canny(xgrad, ygrad, 50, 150)
    cv.imshow("Canny_Edge", edge_output)

    dst = cv.bitwise_and(image, image, mask=edge_output)
    cv.imshow("Color_Edge", dst)

22、直线检测

得到整条直线

def line_detection(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    edges = cv.Canny(gray, 50, 150, apertureSize=3)
    lines = cv.HoughLines(edges, 1, np.pi/180, 200)
    for line in lines:
        rho, theta = line[0]
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a * rho
        y0 = b * rho
        x1 = int(x0 + 1000 * (-b))
        y1 = int(y0 + 1000 * (a))
        x2 = int(x0 - 1000 * (-b))
        y2 = int(y0 - 1000 * (a))
        cv.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2)
    cv.imshow("image-lines", image)

得到线段

def line_detect_possible_demo(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    edges = cv.Canny(gray, 50, 150, apertureSize=3)
    lines = cv.HoughLinesP(edges, 1, np.pi/180, 100, minLineLength=50, maxLineGap=10)
    for line in lines:
        x1, y1, x2, y2 = line[0]
        cv.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2)
    cv.imshow("line_detect_possible_demo", image)

23、提取水平、竖直线

提取水平线

def open_level_demo(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)  # 灰度化
    ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)  # 二值化
    cv.imshow("binary_result", binary)
    kernel = cv.getStructuringElement(cv.MORPH_RECT, (15, 1))  # 结构元素
    binary = cv.morphologyEx(binary, cv.MORPH_OPEN, kernel)
    cv.imshow("open_result", binary)

提取竖直线

def open_vertical_demo(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)  # 灰度化
    ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)  # 二值化
    cv.imshow("binary_result", binary)
    kernel = cv.getStructuringElement(cv.MORPH_RECT, (1, 15))  # 结构元素
    binary = cv.morphologyEx(binary, cv.MORPH_OPEN, kernel)
    cv.imshow("open_result", binary)

24、圆检测

def detect_circle_demo(image):
    dst = cv.pyrMeanShiftFiltering(image, 10, 100)  # 消除噪声
    cimage = cv.cvtColor(dst, cv.COLOR_BGR2GRAY)  # 二值化
    # 霍夫变换提取圆,返回浮点型
    circles = cv.HoughCircles(cimage, cv.HOUGH_GRADIENT, 1, 100, param1=50, param2=30, minRadius=0, maxRadius=0)
    circles = np.uint16(circles)  # 将浮点型转换为整型
    for i in circles[0, :]:
        cv.circle(image, (i[0], i[1]), i[2], (0, 0, 255), 2)  # 画出圆
        cv.circle(image, (i[0], i[1]), 2, (255, 0, 0), 2)  # 画圆心
    cv.imshow("circles", image)

25、 轮廓发现

def contours_demo(image):
    dst = cv.GaussianBlur(image, (3, 3), 0)  # 高斯滤波
    gray = cv.cvtColor(dst, cv.COLOR_BGR2GRAY)  # 转灰度图
    ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)  # 二值化
    cv.imshow("binary_image", binary)

    contours, heriachy = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)  # 获取轮廓
    for i, contour in enumerate(contours):
        print(i)
        # 画出轮廓
        cv.drawContours(image, contours, i, (0, 0, 255), 2)
        # 填充轮廓
        # cv.drawContours(image, contours, i, (0, 0, 255), -1)

    cv.imshow("detect_contours", image)

26、对象测量

def measure_object(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)  # 灰度
    ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)  # 二值化
    cv.imshow("binary_image", binary)
    dst = cv.cvtColor(binary, cv.COLOR_GRAY2BGR)

    contours, heriachy = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)  # 获取轮廓
    for i, contour in enumerate(contours):
        area = cv.contourArea(contour)  # 面积
        print("contour_area: %s" % area)

        x, y, w, h = cv.boundingRect(contour)  # 外接矩形

        rate = min(w, h) / max(w, h)  # 宽高比
        print("rectangle_rate: %s" % rate)

        mm = cv.moments(contour)  # 几何矩
        # 重心
        if mm['m00'] != 0:
            cx = mm['m10'] / mm['m00']
            cy = mm['m01'] / mm['m00']
            cv.circle(dst, (np.int(cx), np.int(cy)), 3, (0, 255, 255), -1)  # 绘制重心

        cv.rectangle(dst, (x, y), (x + w, y + h), (0, 0, 255), 2)  # 绘制外接矩形

        approxCurve = cv.approxPolyDP(contour, 4, True)  # 多边形逼近
        if approxCurve.shape[0] > 6:  # 多边形边大于6就显示
            cv.drawContours(dst, contours, i, (0, 255, 0), 2)
    cv.imshow("measure-contours", dst)

27、膨胀、腐蚀

腐蚀

def erode_demo(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)  #灰度化
    ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)  # 二值化
    kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))  # 结构元素
    dst = cv.erode(binary, kernel)  # 腐蚀
    cv.imshow("erode_demo", dst)

膨胀

def dilate_demo(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)  #灰度化
    ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)  # 二值化
    kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))  # 结构元素
    dst = cv.dilate(binary, kernel)  # 膨胀
    cv.imshow("dilate_demo", dst)

28、开闭操作

开操作:去除小的干扰块 先腐蚀后膨胀

def open_demo(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)  # 灰度化
    ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)  # 二值化
    cv.imshow("binary_result", binary)
    kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))  # 结构元素
    binary = cv.morphologyEx(binary, cv.MORPH_OPEN, kernel)
    cv.imshow("open_result", binary)

闭操作:填充 先膨胀后腐蚀

def close_demo(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)  # 灰度化
    ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)  # 二值化
    cv.imshow("binary_result", binary)
    kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))  # 结构元素
    binary = cv.morphologyEx(binary, cv.MORPH_CLOSE, kernel)
    cv.imshow("close_result", binary)

29、其他形态学操作

顶帽:原图像与开操作之间的差值图像

def top_hat_demo(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)  # 灰度化
    # ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)  # 二值化
    kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))  # 结构元素
    dst = cv.morphologyEx(gray, cv.MORPH_TOPHAT, kernel)  # 顶帽
    # dst = cv.morphologyEx(binary, cv.MORPH_TOPHAT, kernel)  # 顶帽

    cv.imshow("top_hat_demo", dst)

黑帽:闭操作与原图像之间的差值图像

def black_hat_demo(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)  # 灰度化
    # ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)  # 二值化
    kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))  # 结构元素
    dst = cv.morphologyEx(gray, cv.MORPH_BLACKHAT, kernel)  # 黑帽
    # dst = cv.morphologyEx(binary, cv.MORPH_BLACKHAT, kernel)  # 黑帽
    cv.imshow("black_hat_demo", dst)

基准梯度

def datum_gradien_demo(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)  # 灰度化
    ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)  # 二值化
    kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))  # 结构元素
    dst = cv.morphologyEx(binary, cv.MORPH_GRADIENT, kernel)  # 梯度
    cv.imshow("datum_gradien_demo", dst)

内梯度

def internal_gradien_demo(image):
    kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))  # 结构元素
    em = cv.erode(image, kernel)
    dst = cv.subtract(image, em)
    cv.imshow("internal_gradien_demo", dst)

30、分水岭算法(图像分割)

def watershed_demo(src):
    # gray/binary image
    blurred = cv.pyrMeanShiftFiltering(src, 10, 100)
    gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)  # 灰度化
    ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)  # 二值化
    cv.imshow("binary", binary)

    # morphology operation
    kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))  # 结构元素
    mb = cv.morphologyEx(binary, cv.MORPH_OPEN, kernel, iterations=2)  # 2次开操作
    sure_bg = cv.dilate(mb, kernel, iterations=3)  # 3次膨胀
    cv.imshow("mor-opt", sure_bg)

    # distance transform
    dist = cv.distanceTransform(mb, cv.DIST_L2, 3)
    dist_output = cv.normalize(dist, 0, 1.0, cv.NORM_MINMAX)
    cv.imshow("distance-t", dist_output*50)

    ret, surface = cv.threshold(dist, dist.max()*0.6, 255, cv.THRESH_BINARY)
    cv.imshow("surface-bin", surface)

    surface_fg = np.uint8(surface)
    unknown = cv.subtract(sure_bg, surface_fg)
    ret, markers = cv.connectedComponents(surface_fg)

    # watershed transform
    markers = markers + 1
    markers[unknown == 255] = 0
    markers = cv.watershed(src, markers=markers)
    src[markers == -1] = [0, 0, 255]
    cv.imshow("result", src)

31、人脸检测

详见我的另一篇文章。

32、数字验证码识别

详见我的另一篇文章。

码文不易,如果觉得对你有用的话,点个赞再走吧,谢谢宁!

(才疏学浅,如果有什么说的不对的地方,欢迎大家在评论区或者私信进行指正。)

你可能感兴趣的:(c++获取图像的长宽,opencv)