提取图片高频信息

提取图片高频信息

示例-输入:
请添加图片描述
示例-输出:
请添加图片描述
代码实现:

import cv2
import numpy as np


def edge_calc(image):
    src = cv2.GaussianBlur(image, (3, 3), 0)
    ddepth = cv2.CV_16S

    gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
    grad_x = cv2.Scharr(gray, ddepth, 1, 0)
    grad_y = cv2.Scharr(gray, ddepth, 0, 1)

    abs_grad_x = cv2.convertScaleAbs(grad_x)
    abs_grad_y = cv2.convertScaleAbs(grad_y)
    grad = cv2.addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0)
    _, th = cv2.threshold(grad, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    w, h = th.shape[1], th.shape[0]
    cv2.rectangle(th, (0, 0), (w-1, h-1), 255, thickness=12)

    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))  # 定义矩形结构元素
    # th = cv2.morphologyEx(th, cv2.MORPH_DILATE, kernel, iterations=1)  #  膨胀运算1
    edge = cv2.morphologyEx(th, cv2.MORPH_CLOSE, kernel, iterations=1)  # 闭运算1

    # kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))  # 定义矩形结构元素
    # closed = cv2.morphologyEx(th, cv2.MORPH_CLOSE, kernel, iterations=1)  # 闭运算1
    return edge


if __name__ == "__main__":
    img = cv2.imread('paper.png')
    edge = edge_calc(img)
    cv2.imwrite("paper_mask.png", edge.astype(np.uint8))

主要过程包括:平滑、梯度计算、二值化、边框处理,以及形态学操作。

上一篇:操作系统的理解


下一篇:Word和Excel使用有感