使用CV2.imwrite()写入torch类型存储的图片

问题描述:现在有一个torch的数据类型,例如一个(3,512,384)的张量,我们如果想要使用cv2.imwrite()函数来将它写入文件。

首先需要在头文件中导入cv2这个库,即import cv2

然后我们需要对torch类型转换为np类型,并且注意要改变维度为(512,384,3),这样才能作为cv2.imwrite()函数的传入参数

最后使用cv2.imwrite()函数传参即可,该函数有三个参数,我们一般使用前两个(第一个是图片要写入的地址,第二个是对象,例如cv2.imwrite("./gen_image.jpg",image)就是将图像对象image写入当下文件夹的gen_image.jpg中),第三个参数和写入精度有关系,我们一般用不到那个。

# image是一个尺寸为(3,512,384)的张量

image_array = np.transpose(image.numpy(), (1, 2, 0))
print(image_array)
cv2.imwrite("/home/image.png", image_array)

另外,关于写入图片为黑色的问题,参考一位大佬的回答:

一般而言是写入的图像归一化到(0,1)区间内了,只需要*255,将其转换到(0,255)就可以正常的可视化了!

代码如下:

# image是一个尺寸为(3,512,384)的张量

image_array = np.transpose(image.numpy(), (1, 2, 0))
print(image_array)
cv2.imwrite("/home/image.png", image_array * 255)

参考:cv2.imwrite保存的图片是黑色的_cv2.imwrite保存图像是黑色的-CSDN博客

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
代码解释# Process detections for i, det in enumerate(pred): # detections per image if webcam: # batch_size >= 1 p, s, im0 = path[i], '%g: ' % i, im0s[i].copy() else: p, s, im0 = path, '', im0s save_path = str(Path(out) / Path(p).name) s += '%gx%g ' % img.shape[2:] # print string gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh if det is not None and len(det): # Rescale boxes from img_size to im0 size det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round() # Print results for c in det[:, -1].unique(): n = (det[:, -1] == c).sum() # detections per class s += '%g %ss, ' % (n, names[int(c)]) # add to string # Write results for *xyxy, conf, cls in det: if save_txt: # Write to file xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh with open(save_path[:save_path.rfind('.')] + '.txt', 'a') as file: file.write(('%g ' * 5 + '\n') % (cls, *xywh)) # label format if save_img or view_img: # Add bbox to image label = '%s %.2f' % (names[int(cls)], conf) if label is not None: if (label.split())[0] == 'person': people_coords.append(xyxy) # plot_one_box(xyxy, im0, line_thickness=3) plot_dots_on_people(xyxy, im0) # Plot lines connecting people distancing(people_coords, im0, dist_thres_lim=(100, 150)) # Print time (inference + NMS) print('%sDone. (%.3fs)' % (s, t2 - t1)) # Stream results if 1: ui.showimg(im0) if cv2.waitKey(1) == ord('q'): # q to quit raise StopIteration # Save results (image with detections) if save_img: if dataset.mode == 'images': cv2.imwrite(save_path, im0) else: if vid_path != save_path: # new video vid_path = save_path if isinstance(vid_writer, cv2.VideoWriter): vid_writer.release() # release previous video writer fps = vid_cap.get(cv2.CAP_PROP_FPS) w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*opt.fourcc), fps, (w, h)) vid_writer.write(im0)
05-10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值