import torch import torch.nn as nn import cv2 import numpy as np def…
- User
import torch import torch.nn as nn import cv2 import numpy as np
def canny_edge_detection(image): """ 对图像应用Canny边缘检测。 """ # 将图像转换为灰度 gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 执行Canny边缘检测 edges = cv2.Canny(gray_image, 100, 200) return edges
def edge_loss(predictions, targets): """ 计算边缘损失(边缘加权L1损失)。 """ # 对每一张图像进行边缘检测并计算边缘图 edges = canny_edge_detection(targets.astype(np.uint8))
code# 转换边缘图为tensor edge_mask = torch.tensor(edges / 255.0, dtype=predictions.dtype).unsqueeze(0) # Normalize to [0, 1] # 计算 L1 损失 l1_loss = nn.L1Loss(reduction='none')(predictions, targets) # 使用边缘图加权 L1 损失 weighted_loss = l1_loss * edge_mask return weighted_loss.mean() # 返回均值损失def load_image(image_path): """ 从指定路径加载图像,返回的图像为 numpy 数组,形状为 (H, W, C)。 """ image = cv2.imread(image_path) if image is None: raise FileNotFoundError(f"无法加载图像: {image_path}")
code# 将图像从 BGR 转换为 RGB image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # 将图像转换为 float32 类型,并归一化到 [0, 1] image = image.astype(np.float32) / 255.0 return image示例使用
if name == 'main': # 定义图像路径 prediction_image_path = './langen_refine_Test/IMG20240101023257_03_depth_result_aft_smt.png' # 替换为您的预测图像路径 target_image_path = './langan_mask0.3-1/IMG20240101023257_refine.png' # 替换为您的真实图像路径
code# 加载图像 predictions = load_image(prediction_image_path) targets = load_image(target_image_path) # 确保图像大小相同 if predictions.shape != targets.shape: raise ValueError("预测图像和目标图像的尺寸不匹配!") # 将图像转换为张量格式 predictions_tensor = torch.tensor(predictions).unsqueeze(0) # 添加 batch 维度 targets_tensor = torch.tensor(targets).unsqueeze(0)报错Traceback (most recent call last): File "edge-loss.py", line 68, in loss = edge_loss(predictions_tensor, targets_tensor) File "edge-loss.py", line 21, in edge_loss edges = canny_edge_detection(targets.astype(np.uint8)) AttributeError: 'Tensor' object has no attribute 'astype',请使用中文 # 计算边缘损失 loss = edge_loss(predictions_tensor, targets_tensor) print(f'计算得到的边缘损失为: {loss.item()}')
- Assistant
从错误消息来看,代码在尝试使用
astype方法转换一个 PyTorch 张量(Tensor)时出现了问题。astype方法是 NumPy 中的方法,而 PyTorch 张量并没有这个方法。为了修复这个错误,我们需要将张量转换为 NumPy 数组,才能使用
astype方法。你可以使用 来完成这个转换。下面是修复后的代码: - User
Traceback (most recent call last): File "edge-loss.py", line 71, in loss = edge_loss(predictions_tensor, targets_tensor) File "edge-loss.py", line 24, in edge_loss edges = canny_edge_detection(targets_np.astype(np.uint8)) File "edge-loss.py", line 11, in canny_edge_detection gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.error: OpenCV(4.9.0) /io/opencv/modules/imgproc/src/color.simd_helpers.hpp:92: error: (-2:Unspecified error) in function 'cv::impl::{anonymous}::CvtHelper<VScn, VDcn, VDepth, sizePolicy>::CvtHelper(cv::InputArray, cv::OutputArray, int) [with VScn = cv::impl::{anonymous}::Set<3, 4>; VDcn = cv::impl::{anonymous}::Set<1>; VDepth = cv::impl::{anonymous}::Set<0, 2, 5>; cv::impl::{anonymous}::SizePolicy sizePolicy = cv::impl::::NONE; cv::InputArray = const cv::_InputArray&; cv::OutputArray = const cv::_OutputArray&]'
Invalid number of channels in input image: 'VScn::contains(scn)' where 'scn' is 1
- Assistant
- User
输入不一定是三通道,可能是一通道
- Assistant