图像处理——边缘提取
Roberts operator
理论分析
他山之玉 可以攻石,点击这里可以学习相关理论。
版权声明:本文为CSDN博主「TechArtisan6」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zaishuiyifangxym/article/details/89840396
经过一些计算,我们得到Roberts 算子 [[0 , 1], [-1, 0] ] 和 [[1 , 0 ], [0 , -1]]
(与博主的顺序不太一致,但对图片效果没有影响)
编码实现
# -*- coding: utf-8 -*-
# 用简单的算子引出边缘检测的一般流程
import cv2
import numpy as np
import matplotlib.pyplot as plt
def convolution(matrix, c_kernel):
# 正常卷积完后会少半圈(与计算方式有关)
rows, columns = matrix.shape
# 这里提前补上了
result_matrix = matrix.copy().astype(np.int16)
for i in range(0, rows-1):
for j in range(0, columns-1):
result_matrix[i][j] = (result_matrix[i][j]*c_kernel[0][0] +
result_matrix[i+1][j]*c_kernel[1][0] +
result_matrix[i][j+1]*c_kernel[0][1] +
result_matrix[i+1][j+1]*c_kernel[1][1])
return result_matrix
def Roberts_Edge_Detection(source_img):
# 输入灰度图,输出边缘提取后的灰度图
rows, columns = source_img.shape
img = source_img.copy()
# Roberts算子
Roberts_1 = np.array([[0, 1], [-1, 0]], dtype=int)
Roberts_2 = np.array([[1, 0], [0, -1]], dtype=int)
# step2 卷积
x = convolution(img, Roberts_1)
y = convolution(img, Roberts_2)
# 也可以调用cv2的filter2D函数。
# x = cv2.filter2D(img, cv2.CV_16S, Roberts_1)
# y = cv2.filter2D(img, cv2.CV_16S, Roberts_2)
# # 转换卷积后的图片深度,转uint8
absX = cv2.convertScaleAbs(x)
absY = cv2.convertScaleAbs(y)
Roberts_img = np.zeros((rows, columns), dtype=np.uint8)
# 或 Roberts_img = np.array([[0]*columns]*rows).astype(np.uint8)
for i in range(rows):
for j in range(columns):
Roberts_img[i][j] = 0.5*absX[i][j] + 0.5*absY[i][j]
# 或 Roberts = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)
return Roberts_img
if __name__ == "__main__":
# 用imread时需要注意图片路径不要包含中文,否则会can't open/read file: check file path/integrity
# cv2.IMREAD_GRAYSCALE 读入灰度图
source_img = cv2.imread('pictures\\source\\1.jpg', cv2.IMREAD_GRAYSCALE)
# 文件中说In the case of color images, the decoded images will have the channels stored in **B G R** order.彩色图读入BGR
result_img = Roberts_Edge_Detection(source_img)
# 用来正常显示中文标签
plt.rcParams['font.sans-serif'] = ['SimHei']
# plt.imshow()里添加参数cmap=“gray”,显示灰度图
plt.subplot(121), plt.imshow(source_img, cmap="gray"), plt.title('source imge'), plt.axis('off') # 坐标轴关闭
plt.subplot(122), plt.imshow(result_img, cmap="gray"), plt.title('Roberts operator imge'), plt.axis('off')
# 保存图片
plt.savefig('pictures\\result\\1_Roberts operator result.jpg', bbox_inches='tight')
plt.show() # 显示在屏幕上
作者才疏学浅,文章或有不足,请大家多多指教!!!