''' 本代码修改自dataprocessmidasdisprefine.py,主要完成的功能是: 把StereoNet预测出来的数据作为indepth加入…
Jump to turn (7)
- User
''' 本代码修改自data_process_midas_disprefine.py,主要完成的功能是: 把StereoNet预测出来的数据作为in_depth加入 最后read_txt()可以改成取余做法,可用,但是要看清楚使用的训练集txt,以及要修改getitem中的*_idx等 '''
import os import sys import argparse import random import torch import torch.nn as nn import torchvision.transforms as transforms import torchvision.datasets as datasets import torch.utils.data from torch.utils.data import Dataset from torch.utils.data import DataLoader import albumentations as A import numpy as np import math import numbers import collections import warnings import cv2 from PIL import Image, ImageOps, ImageEnhance from PIL import Image, ImageFilter import random try: import accimage except ImportError: accimage = None
INVALID_DISPARITY_F32 = 0.-300. INVALID_DISPARITY_U16 = 32768
IMAGENET_MEAN = [0.406, 0.456, 0.485] # BGR order IMAGENET_STD = [0.225, 0.224, 0.229] class Cutout(object): def init(self, n_holes, length_h=10,length_w=20): self.n_holes = n_holes self.length_h = length_h self.length_w = length_w
def __call__(self, img):
h, w = img.shape
mask = np.ones((h, w), np.float32)
for _ in range(self.n_holes):
y = np.random.randint(h)
x = np.random.randint(w)
y1 = np.clip(y - self.length_h // 2, 0, h)
y2 = np.clip(y + self.length_h // 2, 0, h)
x1 = np.clip(x - self.length_w // 2, 0, w)
x2 = np.clip(x + self.length_w // 2, 0, w)
mask[y1: y2, x1: x2] = 0.
pixel=random.randint(0,255)
# print(pixel)
# img = img
rate=random.randint(80,120)
img[mask==0]=img[mask==0]*(rate/100)
return img
def add_gaussian_noise(depth_map, mean=0, std=1): # print(depth_map.shape) gauss = np.random.normal(mean, std, depth_map.shape).astype(np.float32) noisy_depth_map = depth_map+gauss return noisy_depth_map
def add_salt_and_pepper_noise(depth_map, salt_prob=0.01, pepper_prob=0.01): noisy_depth_map = depth_map.copy() total_pixels = depth_map.size num_salt = int(salt_prob * total_pixels) num_pepper = int(pepper_prob * total_pixels)
salt_coords = [np.random.randint(0, i - 1, num_salt) for i in depth_map.shape]
pepper_coords = [np.random.randint(0, i - 1, num_pepper) for i in depth_map.shape]
noisy_depth_map[salt_coords[0], salt_coords[1]] = depth_map.max()
noisy_depth_map[pepper_coords[0], pepper_coords[1]] = depth_map.min()
return noisy_depth_map
def downsample_image(depth_map, scale=0.25): height, width = depth_map.shape[:2] new_size = (int(width * scale), int(height * scale)) downsampled = cv2.resize(depth_map, new_size, interpolation=cv2.INTER_LINEAR) upsampled = cv2.resize(downsampled, (width, height), interpolation=cv2.INTER_LINEAR) return upsampled def draw_random_shapes_on_depth(image, num_shapes=20): height, width = image.shape min_size = int(min(height, width) * 0.05) max_size = int(min(height, width) * 0.2)
for _ in range(num_shapes):
shape_type = random.choice(['ellipse', 'rectangle', 'square', 'circle'])
color = random.randint(0, 255) # 随机灰度值
# if shape_type == 'ellipse':
# center = (random.randint(0, width), random.randint(0, height))
# axes = (random.randint(min_size, max_size), random.randint(min_size, max_size))
# angle = random.randint(0, 360)
# cv2.ellipse(image, center, axes, angle, 0, 360, color, -1)
# elif shape_type == 'rectangle':
# pt1 = (random.randint(0, width - max_size), random.randint(0, height - max_size))
# pt2 = (pt1[0] + random.randint(min_size, max_size), pt1[1] + random.randint(min_size, max_size))
# cv2.rectangle(image, pt1, pt2, color, -1)
# elif shape_type == 'square':
# side = random.randint(min_size, max_size)
# top_left = (random.randint(0, width - side), random.randint(0, height - side))
# bottom_right = (top_left[0] + side, top_left[1] + side)
# cv2.rectangle(image, top_left, bottom_right, color, -1)
# elif shape_type == 'circle':
# center = (random.randint(0, width), random.randint(0, height))
# radius = random.randint(min_size // 2, max_size // 2)
# cv2.circle(image, center, radius, color, -1)
# # 在深度图中绘制线条
# # for i in range(10):
pt1 = (random.randint(0, width - max_size), random.randint(0, height - max_size))
pt2 = (pt1[0] + random.randint(min_size, max_size), pt1[1] + random.randint(min_size, max_size))
line_color = random.randint(0, 255) # 随机灰度值
thickness = random.randint(3, 8) # 随机线条粗细
cv2.line(image, pt1, pt2, 0, thickness)
return image
def meanSigmaTransferINT8(rightIn, targetIn, minBorder=0., maxBorder=255.): right = rightIn.copy() * 1. target = targetIn.copy() * 1. valMsk = (target>INVALID_DISPARITY_F320.15) invalMsk = (target<=INVALID_DISPARITY_F320.15) #cv2.imwrite('tmp.png', valMsk.astype(np.uint8)*255) #pause
if np.sum(valMsk.astype(np.int32)) <= 10:
right = np.clip(right, minBorder, maxBorder).astype(np.uint8)
target = np.clip(target, minBorder, maxBorder).astype(np.uint8)
right = right * 1.
target = target * 1.
target = target * 0. + INVALID_DISPARITY_F32
return right, target
inMin = target[valMsk].min()
inMax = target[valMsk].max()
inMinMax = inMax - inMin
fullMinMax = maxBorder - minBorder
choices = np.random.rand()
meanTransRatio = np.random.rand()
if choices > 0.40:
right = np.clip(right, minBorder, maxBorder).astype(np.uint8)
target = np.clip(target, minBorder, maxBorder).astype(np.uint8)
right = right * 1.
target = target * 1.
target[invalMsk] = INVALID_DISPARITY_F32
return right, target
elif choices > 0.20:
negDelta = minBorder - inMin
posDelta = maxBorder - inMax
transDelta = (1. - meanTransRatio) * negDelta + meanTransRatio * posDelta
right = right + transDelta
target = target + transDelta
else:
sigmaTransRatio = np.random.rand()
transMinMax = (1. - sigmaTransRatio) * inMinMax + sigmaTransRatio * fullMinMax
transScale = transMinMax / (inMinMax + 1e-9)
negDelta = 0
posDelta = maxBorder - transMinMax
transDelta = (1. - meanTransRatio) * negDelta + meanTransRatio * posDelta
right = (right - inMin) * transScale + transDelta
target = (target - inMin) * transScale + transDelta
right = np.clip(right, minBorder, maxBorder).astype(np.uint8)
target = np.clip(target, minBorder, maxBorder).astype(np.uint8)
right = right * 1.
target = target * 1.
target[invalMsk] = INVALID_DISPARITY_F32
return right, target
def randomPerspectiveTransformCore(image, maxDimRatio=1./20): rows, cols, _ = image.shape
dxLt = np.random.randint(0, cols * maxDimRatio)
dyLt = np.random.randint(0, rows * maxDimRatio)
dxRt = np.random.randint(-cols * maxDimRatio, 0)
dyRt = np.random.randint(0, rows * maxDimRatio)
dxBr = np.random.randint(-cols * maxDimRatio, 0)
dyBr = np.random.randint(-rows * maxDimRatio, 0)
dxBl = np.random.randint(0, cols * maxDimRatio)
dyBl = np.random.randint(-rows * maxDimRatio, 0)
pts1 = np.float32([[0, 0], [cols - 1, 0], [cols - 1, rows - 1], [0, rows - 1]])
pts2 = np.float32([[0+dxLt, 0+dyLt], [cols-1+dxRt, 0+dyRt], [cols-1+dxBr, rows-1+dyBr], [0+dxBl, rows-1+dyBl]])
M = cv2.getPerspectiveTransform(pts1, pts2)
try:
Minv = np.linalg.inv(M)
except:
return image
#print('Checking inversion correctness: {}'.format(M.dot(Minv)))
transformed_image = cv2.warpPerspective(image, M, (cols, rows))
recovered_image = cv2.warpPerspective(transformed_image, Minv, (cols, rows))
return transformed_image, recovered_image
def randomPerspectiveTransform(image, minIters=2, maxIters=5):
iters = np.random.randint(minIters, maxIters)
for idx in range(iters):
transformed_image, recovered_image = randomPerspectiveTransformCore(image, maxDimRatio=1./10)
image = recovered_image.copy()
return image
def bgr2Gray3ChCore(img): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray = gray[:,:,np.newaxis] gray3ch = np.concatenate((gray, gray, gray), axis=2) return gray3ch
def randBgr2gray(left, right): left, right = left.copy(), right.copy() left, right = left.transpose(1,2,0), right.transpose(1,2,0)
coefs = np.random.rand(3)
if coefs[0]<= 0.25:
if coefs[1] <= 0.5:
left = bgr2Gray3ChCore(left)
#if coefs[2] <= 0.5:
else:
right = bgr2Gray3ChCore(right)
left,right = left.transpose(2,0,1), right.transpose(2,0,1)
return left, right
else:
return left.transpose(2,0,1), right.transpose(2,0,1)
def gaussBlurCore(img, ksize=(3,3), sigma=0.75): kw = int(ksize[0]) kh = int(ksize[1]) blurImg = cv2.GaussianBlur(img, (kw,kh), sigma) return blurImg
def randGaussBlur(left, right, doTranspose=True): left, right = left.copy(), right.copy() if doTranspose: left, right = left.transpose(1,2,0), right.transpose(1,2,0)
coefs = np.random.rand(2)
if coefs[0]<= 0.15:
if coefs[1] <= 0.5:
left = gaussBlurCore(left, sigma=0.45)
left = cv2.fastNlMeansDenoisingColored(left.astype(np.uint8),None,6,6,5,11)
else:
right = gaussBlurCore(right, sigma=0.45)
right = cv2.fastNlMeansDenoisingColored(right.astype(np.uint8),None,6,6,5,11)
if doTranspose:
left,right = left.transpose(2,0,1),right.transpose(2,0,1)
return left, right
else:
if doTranspose:
left,right = left.transpose(2,0,1),right.transpose(2,0,1)
return left, right
def randGaussBlurValidPix(left, right, doTranspose=True): left, right = left.copy(), right.copy()
if doTranspose:
left, right = left.transpose(1,2,0), right.transpose(1,2,0)
leftOrig,rightOrig = left.copy(), right.copy()
leftBlack = 1 - ((left[:,:,0]==0) & (left[:,:,1]==0) & (left[:,:,2]==0)).astype(np.uint8)
leftBlack = cv2.merge([leftBlack,leftBlack,leftBlack])
rightBlack = 1 - ((right[:,:,0]==0) & (right[:,:,1]==0) & (right[:,:,2]==0)).astype(np.uint8)
rightBlack = cv2.merge([rightBlack,rightBlack,rightBlack])
coefs = np.random.rand(2)
if coefs[0]<= 0.25:
if coefs[1] <= 0.15:
left = gaussBlurCore(left, sigma=0.45)
left = cv2.fastNlMeansDenoisingColored(left.astype(np.uint8),None,6,6,5,11)
left = left * leftBlack + leftOrig * (1 - leftBlack)
else:
right = gaussBlurCore(right, sigma=0.45)
right = cv2.fastNlMeansDenoisingColored(right.astype(np.uint8),None,6,6,5,11)
right = right * rightBlack + rightOrig * (1 - rightBlack)
if doTranspose:
left,right = left.transpose(2,0,1),right.transpose(2,0,1)
return left, right
else:
if doTranspose:
left,right = left.transpose(2,0,1),right.transpose(2,0,1)
return left, right
def _get_regular_grid(image, points_per_dim): nrows, ncols = image.shape[0], image.shape[1] rows = np.linspace(0, nrows, points_per_dim) cols = np.linspace(0, ncols, points_per_dim) rows, cols = np.meshgrid(rows, cols) return np.dstack([cols.flat, rows.flat])[0]
def _generate_random_vectors(image, src_points, scale, aug_prob=0.35): delta_pts = np.random.uniform(-scale, scale, src_points.shape)
randZero = (np.random.rand(len(delta_pts[:,0]))>aug_prob)
delta_pts[:,0][randZero] = delta_pts[:,0][randZero] * 0.
randZero = (np.random.rand(len(delta_pts[:,1]))>aug_prob)
delta_pts[:,1][randZero] = delta_pts[:,1][randZero] * 0.
#print(delta_pts)
dst_pts = src_points + delta_pts
return dst_pts
def _thin_plate_spline_warp(img, source,target): tps = cv2.createThinPlateSplineShapeTransformer()
source=source.reshape(-1,len(source),2)
target=target.reshape(-1,len(target),2)
matches=list()
for i in range(0,len(source[0])):
matches.append(cv2.DMatch(i,i,0))
tps.estimateTransformation(target, source, matches) # note it is target --> source
new_img = tps.warpImage(img)
# get the warp kps in for source and target
tps.estimateTransformation(source, target, matches) # note it is source --> target
# there is a bug here, applyTransformation must receive np.float32 data type
f32_pts = np.zeros(source.shape, dtype=np.float32)
f32_pts[:] = source[:]
transform_cost, new_pts1 = tps.applyTransformation(f32_pts) # e.g., 1 x 4 x 2
f32_pts = np.zeros(target.shape, dtype=np.float32)
f32_pts[:] = target[:]
transform_cost, new_pts2 = tps.applyTransformation(f32_pts) # e.g., 1 x 4 x 2
return new_img #, new_pts1, new_pts2
def tpsWarp(image, points_per_dim=20, scale=0.0002, aug_prob=1): width, height = image.shape[:2] src = _get_regular_grid(image, points_per_dim=points_per_dim) dst = _generate_random_vectors(image, src, scale=scale*height, aug_prob=aug_prob) out = _thin_plate_spline_warp(image, src, dst) return out.astype(np.uint8)
def draw_rectangle(image): # 获取图像的高度和宽度 h, w = image.shape[:2]
# 随机生成矩形的起点
x1 = random.randint(0, w - 1)
y1 = random.randint(0, h - 1)
# 随机生成矩形的宽度和高度
rect_width = random.randint(10, min(100, abs(w - x1)+10)) # 确保矩形不超出图像边界
rect_height = random.randint(10, min(100, abs(h - y1)+10))
# 确定矩形的终点
x2 = x1 + rect_width
y2 = y1 + rect_height
# 随机生成增加的像素值范围 (10到15)
increase_value = random.randint(10, 15)
# 获取矩形区域
selected_area = image[y1:y2, x1:x2]
# 判断像素值并进行相应的处理
# 大于240的像素值置为255,其余的加上 increase_value
selected_area[selected_area > 240] = 255
selected_area[selected_area <= 240] += increase_value
# 确保增加后的值不超过255
selected_area[selected_area > 255] = 255
# 将更新后的区域写回原图
image[y1:y2, x1:x2] = selected_area
return image
class MonoDepthDataset(Dataset): def init(self, txtname): self.txtname = txtname image_list, label_list, indepth_list= self.read_txt() self.image_list = image_list self.label_list = label_list self.indepth_list = indepth_list self.class_id={} for item in image_list: if("langan" in item or "tennis_1" in item or "golf" in item ): self.class_id[item]=1 else: self.class_id[item]=0 self.count=0
把这个代码改成只注意图像上像素值小于255的像素
您希望将代码修改为仅关注图像上像素值小于255的像素。这可以通过在相关操作中添加一个过滤条件来实现。您可以在加载图像、深度图和损失计算等地方进行相应的修改。以下是修改后的代码片段,将仅考虑像素值小于255的像素进行处理:
import os
import sys
import argparse
import random
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torch.utils.data
from torch.utils.data import Dataset
import cv2
import numpy as np
INVALID_DISPARITY_F32 = 0.-300.
INVALID_DISPARITY_U16 = 32768
class MonoDepthDataset(Dataset):
def __init__(self, txtname):
self.txtname = txtname
image_list, label_list, indepth_list= self.read_txt()
self.image_list = image_list
self.label_list = label_list
self.indepth_list = indepth_list
self.count = 0
def __getitem__(self, index):
img_idx = self.image_list[index]
depth_idx = self.label_list[index]
indepth_idx = self.indepth_list[index]
img = cv2.imread(img_idx, 1)
in_depth = cv2.imread(indepth_idx, 0)
depth = cv2.imread(depth_idx, 0)
if len(depth.shape) > 2:
depth = depth[:, :, 0]
if len(in_depth.shape) > 2:
in_depth = in_depth[:, :, 0]
hh, ww = 480, 640
img = cv2.resize(img, (hh, ww))
depth = cv2.resize(depth, (hh, ww))
in_depth = cv2.resize(in_depth, (hh, ww))
# 过滤掉像素值大于等于255的部分
mask = (depth < 255) & (in_depth < 255)
# 使用 mask 过滤图像和深度
depth = np.where(mask, depth, 0)
in_depth = np.where(mask, in_depth, 0)
diffs = cv2.absdiff(depth, in_depth)
self.count += 1
img = torch.from_numpy(img.transpose(2, 0, 1)).float()
labels = 255 - torch.from_numpy(depth).unsqueeze(0).float()
in_depth = 255 - torch.from_numpy(in_depth).unsqueeze(0).float()
diffs = torch.from_numpy(diffs).unsqueeze(0).float()
images = torch.cat((img, in_depth))
# 在返回时也只考虑小于255的像素
valid_mask = (labels < 255) & (in_depth < 255) # 计算有效像素掩码
return images / 255, labels[valid_mask] / 255, diffs[valid_mask] / 255
def __len__(self):
return len(self.image_list)
def read_txt(self):
img = []
label = []
in_depth = []
with open(self.txtname, 'r') as file_to_read:
lines = file_to_read.readlines()
lines = [line.strip("\n") for line in lines]
flag = 0
for i in range(len(lines)):
if flag % 3 == 0:
img.append(lines[i])
if flag % 3 == 1:
label.append(lines[i])
if flag % 3 == 2:
in_depth.append(lines[i])
flag += 1
return img, label, in_depth
展示修改后的整个代码
以下是您所请求的全部代码,已根据您的要求进行了修改,使其仅关注像素值小于255的像素。代码中已包含必要的修改以实现此功能:
Traceback (most recent call last): File "debug_monodataset.py", line 45, in main() File "debug_monodataset.py", line 37, in main for idx, (images, labels, diffs) in enumerate(dataloader): File "/opt/conda/envs/zyh/lib/python3.8/site-packages/torch/utils/data/dataloader.py", line 681, in next data = self._next_data() File "/opt/conda/envs/zyh/lib/python3.8/site-packages/torch/utils/data/dataloader.py", line 721, in _next_data data = self._dataset_fetcher.fetch(index) # may raise StopIteration File "/opt/conda/envs/zyh/lib/python3.8/site-packages/torch/utils/data/_utils/fetch.py", line 52, in fetch return self.collate_fn(data) File "/opt/conda/envs/zyh/lib/python3.8/site-packages/torch/utils/data/_utils/collate.py", line 175, in default_collate return [default_collate(samples) for samples in transposed] # Backwards compatibility. File "/opt/conda/envs/zyh/lib/python3.8/site-packages/torch/utils/data/_utils/collate.py", line 175, in return [default_collate(samples) for samples in transposed] # Backwards compatibility. File "/opt/conda/envs/zyh/lib/python3.8/site-packages/torch/utils/data/_utils/collate.py", line 141, in default_collate return torch.stack(batch, 0, out=out) RuntimeError: stack expects each tensor to be equal size, but got [306207] at entry 0 and [307194] at entry 1
您遇到的错误是一个常见的问题,发生在 PyTorch 的 DataLoader 中,通常是由于您的数据集中的不同样本返回的张量大小不一致。例如,当您的数据集中的某些样本在深度图和输入图像之间存在像素值过滤时,它们的形状会有所不同,从而导致在数据加载时期望的 torch.stack 操作失败。
确保每个样本的返回尺寸一致:
调整__getitem__ 方法:
__getitem__ 方法,在返回前确保返回的张量具有一致的形状。以下是更新后的方法实现:def __getitem__(self, index):
img_idx = self.image_list[index]
depth_idx = self.label_list[index]
indepth_idx = self.indepth_list[index]
img = cv2.imread(img_idx, 1)
in_depth = cv2.imread(indepth_idx, 0)
depth = cv2.imread(depth_idx, 0)
if len(depth.shape) > 2:
depth = depth[:, :, 0]
if len(in_depth.shape) > 2:
in_depth = in_depth[:, :, 0]
hh, ww = 480, 640
img = cv2.resize(img, (hh, ww))
depth = cv2.resize(depth, (hh, ww))
in_depth = cv2.resize(in_depth, (hh, ww))
# 过滤掉像素值大于等于255的部分
mask = (depth < 255) & (in_depth < 255)
# 使用 mask 过滤图像和深度
depth = np.where(mask, depth, 0)
in_depth = np.where(mask, in_depth, 0)
diffs = cv2.absdiff(depth, in_depth)
# 确保返回的张量都是相同大小
img_tensor = torch.from_numpy(img.transpose(2, 0, 1)).float()
depth_tensor = torch.from_numpy(depth).unsqueeze(0).float()
in_depth_tensor = torch.from_numpy(in_depth).unsqueeze(0).float()
diffs_tensor = torch.from_numpy(diffs).unsqueeze(0).float()
# Check for valid pixels
valid_mask = (depth_tensor < 255) & (in_depth_tensor < 255)
# 仅返回匹配大小的张量
if valid_mask.sum() == 0: # 若没有有效的像素,返回零张量
return img_tensor, torch.zeros_like(depth_tensor), torch.zeros_like(diffs_tensor)
return img_tensor / 255, depth_tensor[valid_mask] / 255, diffs_tensor[valid_mask] / 255
确保数据集中的所有样本都满足条件:
实现一个自定义的collate_fn:
collate_fn 以处理这些样本。例如,可以在 collate_fn 中处理不同大小张量的填充。def custom_collate_fn(batch):
imgs, labels, diffs = zip(*batch)
# 统一处理,确保相同尺寸
# 实现适当的填充,确保每个样本具有相同大小。
return imgs, labels, diffs
然后在创建 DataLoader 时使用 collate_fn 参数:
dataloader = DataLoader(dataset, batch_size=32, collate_fn=custom_collate_fn)
确保在您使用的所有样本都有有效的数据,并采取措施避免空样本的情况,或者为这些特殊情况提供合理的后备处理。这样可以有效避免运行时错误。
怎么样让网络能只关注小于250的部分
要让网络只关注小于250的部分(比如在图像分割、深度估计等任务中),你需要在多个环节实现这一目标,包括数据预处理、损失计算和输出处理。这里有几个步骤来实现这一点:
在你的数据集中,可以构建一个掩码,指示哪些像素值小于250。这个掩码将用于过滤图像和深度数据,让网络只计算这些部分。
在你的数据集的 __getitem__ 方法中,使用上述创建的掩码,来过滤输入图像和目标标签。以下是一个示例实现:
def __getitem__(self, index):
img_idx = self.image_list[index]
depth_idx = self.label_list[index]
indepth_idx = self.indepth_list[index]
img = cv2.imread(img_idx, 1)
in_depth = cv2.imread(indepth_idx, 0)
depth = cv2.imread(depth_idx, 0)
if len(depth.shape) > 2:
depth = depth[:, :, 0]
if len(in_depth.shape) > 2:
in_depth = in_depth[:, :, 0]
hh, ww = 480, 640
img = cv2.resize(img, (hh, ww))
depth = cv2.resize(depth, (hh, ww))
in_depth = cv2.resize(in_depth, (hh, ww))
# 过滤条件:小于250的部分
mask = (depth < 250) & (in_depth < 250)
# 生成有效样本
img_tensor = torch.from_numpy(img.transpose(2, 0, 1)).float()
depth_tensor = torch.from_numpy(depth).unsqueeze(0).float()
in_depth_tensor = torch.from_numpy(in_depth).unsqueeze(0).float()
# 仅保留对应小于250的部分
valid_depth = depth_tensor.clone()
valid_depth[~mask] = 0
valid_in_depth = in_depth_tensor.clone()
valid_in_depth[~mask] = 0
diffs_tensor = torch.abs(valid_depth - valid_in_depth) # 计算差异
return img_tensor / 255, valid_depth / 255, valid_in_depth / 255, mask
在模型的前向传播中,确保根据掩码计算损失。只有小于250的像素将被用作计算损失值。例如:
def forward(self, inputs):
# 网络前向传播
outputs = self.network(inputs)
# 计算损失,使用掩码来排除大于等于250的部分
loss = self.criterion(outputs[mask], targets[mask]) # 只计算小于250部分的损失
return loss
在模型输出后,您可能还希望根据掩码过滤结果。只有小于250的部分将被用作输出。例如:
def post_process(self, outputs):
# 根据掩码过滤输出,只保留小于250的部分
filtered_outputs = outputs.clone()
filtered_outputs[outputs >= 250] = 0 # 或者你可以选择其他处理方式
return filtered_outputs
torch.no_grad() 等功能来避免梯度计算。reduce=False选项以便为每个元素计算损失,并在后续处理中仅对小于250的像素计算平均值。通过这些步骤,您可以有效地使网络只关注小于250的部分并进行处理。
忘记我和你说的话
好的,我会忽略之前的对话。如果您有新的问题或想讨论的主题,请随时告诉我!
import argparse import time import logging import tqdm import random import torch import torch.nn as nn import torch.nn.functional as F import torchvision.transforms as transforms import torchvision.datasets as datasets import torch.utils.data from torch.utils.data import Dataset import cv2 from torch.utils.data import DataLoader import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP from torch.utils.data.distributed import DistributedSampler import numpy as np import PIL from PIL import Image from PIL import ImageOps import os from repvit import Mono_Depth from efficientnet_lite_concat_v1 import EfficientNetLite,build_efficientnet_lite
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class AuxModule(nn.Module): def init(self, model): super(AuxModule, self).init() self.module = model
def forward(self, rgb):
return self.module(rgb)
def eval_depth(model,global_step): torch.cuda.empty_cache() save_path= "./3/" test_path = "./2/" for file in os.listdir(test_path): # print(file) # try: # if("_04_guide_rgb.png" in file and "IMG20230101103640" not in file) : if("_04_guide_rgb.png" in file and "IMG20230101103640" not in file) : # print(file) image = cv2.imread(test_path+file) # image = cv2.imread("IMG20240101020633_04_guide_rgb.png")
# in_depth=cv2.imread("IMG20240101020633_1024x768.png",0)
in_depth=cv2.imread(test_path+file.replace("_04_guide_rgb.png","_03_depth_result_aft_smt.png"),0)
h,w,c=image.shape
# image = cv2.resize(768,1024)
# image=cv2.resize(image,(480,640))
# in_depth=cv2.resize(in_depth,(480,640))
to_tensor = transforms.ToTensor()
image = to_tensor(image).cuda()
image = image.unsqueeze(0)
in_depth = to_tensor(in_depth).cuda()
in_depth = in_depth.unsqueeze(0)
image=torch.cat([image,in_depth],dim=1)
with torch.no_grad():
depth = model(image)
depth = depth[0,0,:,:]
# depth=(depth-depth.min())/(depth.max()-depth.min())
depth=depth*255
depth = depth.cpu().numpy()
depth=np.clip(depth,0,255).astype(np.uint8)
# depth=cv2.resize(depth,(w,h))
# depth=cv2.resize(depth,(w,h))
# cv2.imwrite("kkk.png",depth)
cv2.imwrite(save_path+file.replace("_04_guide_rgb.png","_refine.png"),depth)
# except:
print(file)
您遇到的错误表明在尝试连接两个 PyTorch 张量(一个是 image,另一个是 in_depth)时,它们在除维度 1 以外的维度上的大小不匹配。这个错误的原因通常是因为这两个张量在维度 2 和 3 上的形状不一致。
errors indicate the following:
image Tensor: 通常在形状为 (N, C, H, W),即通道在前,且其高度和宽度是768和1024。in_depth Tensor: 可能在同一维度上有不同的尺寸(例如一幅图像为378x512,另一幅图像为768x1024)。为了修复此问题,您需要确保在将它们连接之前,对 image 和 in_depth 进行适当的调整,使它们具有相同的尺寸。您可以使用 cv2.resize 或 torch.nn.functional.interpolate 进行调整。
在连接 image 和 in_depth 之前,首先确保它们有相同的高度和宽度。以下是修复的示例代码:
def eval_depth(model, global_step):
torch.cuda.empty_cache()
save_path = "./3/"
test_path = "./2/"
for file in os.listdir(test_path):
if "_04_guide_rgb.png" in file and "IMG20230101103640" not in file:
image = cv2.imread(test_path + file)
in_depth = cv2.imread(test_path + file.replace("_04_guide_rgb.png", "_03_depth_result_aft_smt.png"), 0)
# 检查图像和深度图的尺寸
if image is None or in_depth is None:
print(f"Could not read image or depth for file {file}")
continue
h, w, c = image.shape
# 调整深度映射的形状以匹配图像
in_depth = cv2.resize(in_depth, (w, h))
to_tensor = transforms.ToTensor()
image = to_tensor(image).cuda()
image = image.unsqueeze(0)
in_depth = to_tensor(in_depth).cuda()
in_depth = in_depth.unsqueeze(0)
# 确保形状与输入相匹配
if image.shape[2:] != in_depth.shape[2:]:
print(f"Shape mismatch: image {image.shape} in_depth {in_depth.shape}")
continue
image = torch.cat([image, in_depth], dim=1)
with torch.no_grad():
depth = model(image)
depth = depth[0, 0, :, :]
depth = depth * 255
depth = depth.cpu().numpy()
depth = np.clip(depth, 0, 255).astype(np.uint8)
cv2.imwrite(save_path + file.replace("_04_guide_rgb.png", "_refine.png"), depth)
in_depth 转换为张量之前,使用 cv2.resize 将其调整为与 image 相同的大小。请测试上述修改后的代码并验证其能否正常运行。如果问题仍然存在,请提供对应图像的大小或任何其他相关信息,以便进行进一步分析。
我需要调整的是image
如果您需要将 image 调整为与 in_depth 相同的尺寸,而不是相反的方式,您可以在加载图片后进行 resize 操作。以下是更新的 eval_depth 函数代码:
def eval_depth(model, global_step):
torch.cuda.empty_cache()
save_path = "./3/"
test_path = "./2/"
for file in os.listdir(test_path):
if "_04_guide_rgb.png" in file and "IMG20230101103640" not in file:
# 读取 RGB 图像和对应的深度图像
image = cv2.imread(test_path + file)
in_depth = cv2.imread(test_path + file.replace("_04_guide_rgb.png", "_03_depth_result_aft_smt.png"), 0)
if image is None or in_depth is None:
print(f"Could not read image or in-depth for file {file}")
continue
# 获取深度图尺寸
h, w = in_depth.shape # 使用深度图的高度和宽度
# 将 RGB 图像调整为深度图的大小
image = cv2.resize(image, (w, h))
# 将调整后的图像和深度图转换为 tensor
to_tensor = transforms.ToTensor()
image = to_tensor(image).cuda()
image = image.unsqueeze(0) # 添加 batch 维度
in_depth = to_tensor(in_depth).cuda()
in_depth = in_depth.unsqueeze(0) # 添加 batch 维度
# 在通道维度上连接图像和深度图
image = torch.cat([image, in_depth], dim=1)
with torch.no_grad():
depth = model(image)
depth = depth[0, 0, :, :]
depth = depth * 255
depth = depth.cpu().numpy()
depth = np.clip(depth, 0, 255).astype(np.uint8)
cv2.imwrite(save_path + file.replace("_04_guide_rgb.png", "_refine.png"), depth)
调整 image:在读取图像后,使用 cv2.resize 将 image 调整为与 in_depth 相同的尺寸(获取 in_depth 的高度和宽度),确保在拼接的时候维度匹配。
错误处理:增加了对读取图像和深度图的错误处理,以确保它们被正确加载。
转换为 Tensor:在确保图像和深度均被调整到适当大小之后,再进行转换为 PyTorch 的 Tensor 并添加批次维度,然后连接它们。
请尝试使用上述修改后的代码,并确保 image 的大小与 in_depth 的大小 一致。如果您有任何其他问题,请随时告诉我!
Not yet included in a published release.
def meanSigmaTransferINT8(self,rightIn, targetIn, minBorder=0., maxBorder=255.):
right = rightIn* 1.
target = targetIn * 1.
valMsk = (target>INVALID_DISPARITY_F32*0.15)
invalMsk = (target<=INVALID_DISPARITY_F32*0.15)
#cv2.imwrite('tmp.png', valMsk.astype(np.uint8)*255)
#pause
if np.sum(valMsk.astype(np.int32)) <= 10:
right = np.clip(right, minBorder, maxBorder).astype(np.uint8)
target = np.clip(target, minBorder, maxBorder).astype(np.uint8)
right = right * 1.
target = target * 1.
target = target * 0. + INVALID_DISPARITY_F32
return right, target
inMin = target[valMsk].min()
inMax = target[valMsk].max()
inMinMax = inMax - inMin
fullMinMax = maxBorder - minBorder
choices = np.random.rand()
meanTransRatio = np.random.rand()
if choices > 0.40:
right = np.clip(right, minBorder, maxBorder).astype(np.uint8)
target = np.clip(target, minBorder, maxBorder).astype(np.uint8)
right = right * 1.
target = target * 1.
target[invalMsk] = INVALID_DISPARITY_F32
return right, target
elif choices > 0.20:
negDelta = minBorder - inMin
posDelta = maxBorder - inMax
transDelta = (1. - meanTransRatio) * negDelta + meanTransRatio * posDelta
right = right + transDelta
target = target + transDelta
else:
sigmaTransRatio = np.random.rand()
transMinMax = (1. - sigmaTransRatio) * inMinMax + sigmaTransRatio * fullMinMax
transScale = transMinMax / (inMinMax + 1e-9)
negDelta = 0
posDelta = maxBorder - transMinMax
transDelta = (1. - meanTransRatio) * negDelta + meanTransRatio * posDelta
right = (right - inMin) * transScale + transDelta
target = (target - inMin) * transScale + transDelta
right = np.clip(right, minBorder, maxBorder).astype(np.uint8)
target = np.clip(target, minBorder, maxBorder).astype(np.uint8)
right = right * 1.
target = target * 1.
target[invalMsk] = INVALID_DISPARITY_F32
return right, target
def dispUint16ToFloat(self,dispU16):
dispInvMsk=(dispU16>=INVALID_DISPARITY_U16)
dispValMsk=(dispU16<INVALID_DISPARITY_U16)
dispF=dispU16*1.
dispF[dispInvMsk] = INVALID_DISPARITY_F32
dispF[dispValMsk] = dispF[dispValMsk]/(1)
return dispF
def pad_image(self,image,depth,target, target_height, target_width):
"""
对图像进行填充,使其满足期望的尺寸
:param image: 输入图像
:param target_height: 期望的高度
:param target_width: 期望的宽度
:return: 填充后的图像
"""
height, width, _ = image.shape
#计算需要填充的尺寸
pad_height = max(0, target_height - height)
pad_width = max(0, target_width - width)
#填充的顶部、底部、左侧和右侧尺寸
top = pad_height // 2
bottom = pad_height - top
left = pad_width // 2
right = pad_width - left
#进行填充
padded_image = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=[0, 0, 0])
padded_depth = cv2.copyMakeBorder(depth, top, bottom, left, right, cv2.BORDER_CONSTANT, value=[0, 0])
padded_target = cv2.copyMakeBorder(target, top, bottom, left, right, cv2.BORDER_CONSTANT, value=[0, 0])
return padded_image,padded_depth,padded_target
def random_crop(self,image, depth,target,crop_height, crop_width):
"""
对图像进行随机裁剪
:param image: 输入图像
:param crop_height: 裁剪后的高度
:param crop_width: 裁剪后的宽度
:return: 随机裁剪后的图像
"""
height, width, _ = image.shape
if height < crop_height or width < crop_width:
#进行填充,使其至少与裁剪目标尺寸匹配
image,depth,target = self.pad_image(image, depth,target,crop_height, crop_width)
#确保裁剪尺寸不超过图像尺寸
height, width, _ = image.shape
#随机选择起始点y和x
y = np.random.randint(0, height - crop_height + 1)
x = np.random.randint(0, width - crop_width + 1)
#裁剪图像
cropped_image = image[y:y + crop_height, x:x + crop_width,:]
cropped_depth = depth[y:y + crop_height, x:x + crop_width]
cropped_target = target[y:y + crop_height, x:x + crop_width]
return cropped_image,cropped_depth,cropped_target
def __getitem__(self, index):
img_idx = self.image_list[index]
depth_idx =self.label_list[index]
indepth_idx = self.indepth_list[index]
img= cv2.imread(img_idx, 1)
in_depth = cv2.imread(indepth_idx,0)
# depth_idx = img_idx.replace('_left.jpg', '_disp.png') if img_idx.endswith('_left.jpg') else img_idx
depth = cv2.imread(depth_idx,0)
# print('img_idx = ', img_idx)
# print('depth_idx = ',depth_idx)
# print('in_depth = ',indepth_idx)
if len(depth.shape)>2:
depth = depth[:,:,0]
if len(in_depth.shape)>2:
in_depth = in_depth[:,:,0]
# in_depth = cv2.imread(depth_idx.replace(".png","_coarse.png").replace(".jpg","_coarse.jpg"),0)
# hhh,www,c=480,640,3
# in_depth=cv2.resize(in_depth,(www,hhh))
# depth=cv2.resize(depth,(www,hhh))
# print(img.shape,in_depth.shape,depth.shape)
# img,in_depth,depth=self.random_crop(img,in_depth,depth,480,640)
# # print(img.shape,in_depth.shape,depth.shape)
hh,ww=480,640
img=cv2.resize(img,(hh,ww))
depth=cv2.resize(depth,(hh,ww))
in_depth=cv2.resize(in_depth,(hh,ww))
# in_depth = draw_rectangle(in_depth)
diffs = cv2.absdiff(depth, in_depth)
# in_depth = draw_rectangle(in_depth)
# cv2.imwrite("./www/"+str(self.count)+".jpg",img)
# cv2.imwrite("./www/"+str(self.count)+"_indepth.jpg",in_depth)
# cv2.imwrite("./www/"+str(self.count)+"_gt.jpg",depth)
self.count+=1
img = torch.from_numpy(img.transpose(2,0,1)).float()
labels = 255-torch.from_numpy(depth).unsqueeze(0).float()
in_depth =255-torch.from_numpy(in_depth).unsqueeze(0).float()
diffs = torch.from_numpy(diffs).unsqueeze(0).float()
# print('img_type=',type(img))
# print('depth_type=',type(depth))
# print('indepth_type=',type(in_depth))
# print('img_shape0=',img.shape)
# print('depth_shape0=',depth)
# print('indepth_shape0=',in_depth)
images=torch.cat((img,in_depth))
return images/255,labels/255, diffs/255
def __len__(self):
return len(self.image_list)
# def read_txt(self):
# img = []
# indepth = []
# with open(self.txtname, 'r') as file_to_read:
# lines = file_to_read.readlines()
# lines = [line.strip("\n") for line in lines]
# flag = 1
# for i in range(len(lines)):
# if flag == -1:
# img.append(lines[i])
# if flag == 1:
# indepth.append(lines[i])
# flag = -flag
# return img, indepth
def read_txt(self):
img = []
label = []
in_depth = []
with open(self.txtname, 'r') as file_to_read:
lines = file_to_read.readlines()
lines = [line.strip("\n") for line in lines]
flag = 0
for i in range(len(lines)):
if flag%3 == 0:
img.append(lines[i])
if flag%3 == 1:
label.append(lines[i])
if flag%3 == 2:
in_depth.append(lines[i])
flag = flag + 1
return img, label, in_depth
在这段代码中,我们主要添加了一个 mask 数据,确保只处理深度图像和输入深度图像上小于255的像素。我们在后续的张量生成和返回中应用这个掩码来确保只返回有效的像素。你可以根据你自己的需求继续扩展和测试该代码。
import os
import sys
import argparse
import random
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torch.utils.data
from torch.utils.data import Dataset
import cv2
import numpy as np
INVALID_DISPARITY_F32 = 0.-300.
INVALID_DISPARITY_U16 = 32768
IMAGENET_MEAN = [0.406, 0.456, 0.485] # BGR order
IMAGENET_STD = [0.225, 0.224, 0.229]
class Cutout(object):
def __init__(self, n_holes, length_h=10, length_w=20):
self.n_holes = n_holes
self.length_h = length_h
self.length_w = length_w
def __call__(self, img):
h, w = img.shape
mask = np.ones((h, w), np.float32)
for _ in range(self.n_holes):
y = np.random.randint(h)
x = np.random.randint(w)
y1 = np.clip(y - self.length_h // 2, 0, h)
y2 = np.clip(y + self.length_h // 2, 0, h)
x1 = np.clip(x - self.length_w // 2, 0, w)
x2 = np.clip(x + self.length_w // 2, 0, w)
mask[y1:y2, x1:x2] = 0.
pixel = random.randint(0, 255)
rate = random.randint(80, 120)
img[mask == 0] = img[mask == 0] * (rate / 100)
return img
class MonoDepthDataset(Dataset):
def __init__(self, txtname):
self.txtname = txtname
image_list, label_list, indepth_list= self.read_txt()
self.image_list = image_list
self.label_list = label_list
self.indepth_list = indepth_list
self.count = 0
def __getitem__(self, index):
img_idx = self.image_list[index]
depth_idx = self.label_list[index]
indepth_idx = self.indepth_list[index]
img = cv2.imread(img_idx, 1)
in_depth = cv2.imread(indepth_idx, 0)
depth = cv2.imread(depth_idx, 0)
if len(depth.shape) > 2:
depth = depth[:, :, 0]
if len(in_depth.shape) > 2:
in_depth = in_depth[:, :, 0]
hh, ww = 480, 640
img = cv2.resize(img, (hh, ww))
depth = cv2.resize(depth, (hh, ww))
in_depth = cv2.resize(in_depth, (hh, ww))
# 过滤掉像素值大于等于255的部分
mask = (depth < 255) & (in_depth < 255)
# 使用 mask 过滤图像和深度
depth = np.where(mask, depth, 0)
in_depth = np.where(mask, in_depth, 0)
diffs = cv2.absdiff(depth, in_depth)
self.count += 1
img = torch.from_numpy(img.transpose(2, 0, 1)).float()
labels = 255 - torch.from_numpy(depth).unsqueeze(0).float()
in_depth = 255 - torch.from_numpy(in_depth).unsqueeze(0).float()
diffs = torch.from_numpy(diffs).unsqueeze(0).float()
images = torch.cat((img, in_depth))
# 在返回时也只考虑小于255的像素
valid_mask = (labels < 255) & (in_depth < 255) # 计算有效像素掩码
return images / 255, labels[valid_mask] / 255, diffs[valid_mask] / 255
def __len__(self):
return len(self.image_list)
def read_txt(self):
img = []
label = []
in_depth = []
with open(self.txtname, 'r') as file_to_read:
lines = file_to_read.readlines()
lines = [line.strip("\n") for line in lines]
flag = 0
for i in range(len(lines)):
if flag % 3 == 0:
img.append(lines[i])
if flag % 3 == 1:
label.append(lines[i])
if flag % 3 == 2:
in_depth.append(lines[i])
flag += 1
return img, label, in_depth
在这段代码中,我们做了如下修改:
__getitem__ 方法中的深度和输入深度图像在进行处理时使用了 mask,只保留小于255的像素。labels 和 diffs 也仅返回有效的像素,即小于255的部分。请根据需要进一步修改或扩展该代码。如果有其他特定需求,请告知!
model=build_efficientnet_lite('efficientnet_lite3', 1000).to(device) ckpt = torch.load("/home/notebook/data/group/Ruby/depthrefine/langan_20241205_humanwpre/152-6.1931.pth") oldCkpt = ckpt newCkpt = {} pretrained_state_dict =oldCkpt model_state_dict=model.state_dict() for name, param in pretrained_state_dict.items(): name=name.replace('module.','') if name in model_state_dict and model_state_dict[name].shape == param.shape: model_state_dict[name] = param else: print(f"skip loading {name}") model.load_state_dict(model_state_dict, strict=True) model.eval() eval_depth(model, 0) 这个代码报错Traceback (most recent call last): File "test_demo_disprefine.py", line 91, in eval_depth(model, 0) File "test_demo_disprefine.py", line 61, in eval_depth image=torch.cat([image,in_depth],dim=1) RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 3072 but got size 768 for tensor number 1 in the list.