利用opencv实现canny算法图像边缘提取

利用opencv实现canny算法图像边缘提取

canny算法

Canny算法步骤:
        ①高斯模糊 - GaussianBlur
        ②灰度转换 - cvtColor
        ③计算梯度 – Sobel/Scharr
        ④非最大信号抑制
        ⑤高低阈值输出二值图像——高低阈值比值为2:1或3:1最佳

边缘提取函数

cv2.GaussianBlur
cv2.Sobel

import cv2
def Opencv_canny_edge_extraction(img):
    #img: 原图像
    #return 黑白边缘,彩色边缘
    gaus = cv2.GaussianBlur(img, (3, 3), 0) #高斯模糊
    gray = cv2.cvtColor(gaus,cv2.COLOR_BGR2GRAY) #灰度化
    gradx = cv2.Sobel(gray, cv2.CV_16SC1, 1, 0) 
    grady = cv2.Sobel(gray, cv2.CV_16SC1, 0, 1)
    edge_out = cv2.Canny(gradx, grady, 50, 150)  #黑白的边缘 高低阈值比值为2:1或3:1最佳(50:150 = 1:3)
    dst = cv2.bitwise_and(img, img,mask=edge_out)  # 彩色的边缘
    return edge_out,dst 

应用

物体提取

我尝试利用彩色边缘提取,再结合滑动窗口的方式来确定疑似目标在图片中的位置
画出矩形框
Numpy的数组各行,各列的求和,平均值,最大值,最小值,最大最小值差,标准差,方差等的计算
算法:
1.将图片分为m×n个矩形区域
2.计算每个矩形区域的像素和
3.根据像素和求每个区域的近似微分,舍弃边缘区域
4.筛选极大值作为疑似目标区域中心

非常抱歉,我之前提供的代码存在错误。在 PyTorch 中,并没有直接提供离散余弦变换(DCT)的函数。对于 DCT 的实现,你可以使用 `torch.rfft` 函数结合 DCT 系数矩阵来进行计算。 下面是一个修正后的示例代码: ```python import torch import torch.nn as nn import torch.optim as optim # 定义离散余弦变换(DCT)系数矩阵 dct_matrix = torch.zeros(256, 256) for i in range(256): for j in range(256): dct_matrix[i, j] = torch.cos((2 * i + 1) * j * 3.14159 / (2 * 256)) # 定义 OMP 算法 def omp(A, y, k): m, n = A.shape x = torch.zeros(n, 1) residual = y.clone() support = [] for _ in range(k): projections = torch.abs(A.t().matmul(residual)) index = torch.argmax(projections) support.append(index) AtA_inv = torch.linalg.inv(A[:, support].t().matmul(A[:, support])) x_new = AtA_inv.matmul(A[:, support].t()).matmul(y) residual = y - A[:, support].matmul(x_new) x[support] = x_new return x # 加载原始图像 image = torch.randn(256, 256) # 压缩感知成像 measurement_matrix = torch.fft.fft(torch.eye(256), dim=0).real compressed = measurement_matrix.matmul(image.flatten().unsqueeze(1)) # 使用 OMP 进行重构 reconstructed = omp(dct_matrix, compressed, k=100) # 计算重构误差 mse = nn.MSELoss() reconstruction_error = mse(image, reconstructed.reshape(image.shape)) print("重构误差:", reconstruction_error.item()) ``` 在这个示例中,我们手动定义了 DCT 系数矩阵 `dct_matrix`,然后使用 `torch.fft.fft` 函数计算测量矩阵,并进行实部提取。接下来的步骤与之前的示例相同。 请注意,这只是一个示例,用于演示如何使用自定义的 DCT 系数矩阵进行压缩感知成像。在实际应用中,你可能需要根据具体的需求进行调整和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值