cv2.show显示图片空白

源程序如下:

import numpy as np
from cv2 import cv2
import os
import matplotlib.pyplot as plt
#初始化一个图像数组
img = np.zeros(shape=(960, 720))

#root:当前正在遍历的这个文件夹的本身的地址
#dirs:该文件夹中所有的目录的名字(不包括子目录)
#files:该文件夹中所有的文件
for root, dirs, files in os.walk("./img"):
    for i in range(20):
        path = "./img/" + files[i]
        img += cv2.imread(path, 0)
print(img / 20)
img = img / 20

#plt显示图片方法,不用除以255
# plt.imshow(img, cmap='gray')
# plt.show()

#opencv显示图片方法,要用img/255
img=img/255
cv2.imshow("img",img)
cv2.waitKey(0)

程序的目的是读取文件夹中20张图片,并把每个图片对应像素点进行叠加,在取平均,取完平均值后的图像矩阵为float类型。

使用cv2.imshow读取图片并显示,图片全部空白。打开imshow函数

BUG分析:注释写道如果图片是float型,为了保持图像精度,像素矩阵将乘以255, 所以对于原图像矩阵,显示都是为白色了。

解决方法:原图像除以255

 其他方案:使用plt.imshow(img, cmap='gray'),直接可以显示图片

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
from skimage.segmentation import slic, mark_boundaries import torchvision.transforms as transforms import numpy as np from PIL import Image import matplotlib.pyplot as plt import cv2 # 加载图像 image = Image.open('img.png') # 转换为 PyTorch 张量 transform = transforms.ToTensor() img_tensor = transform(image).unsqueeze(0) # 将 PyTorch 张量转换为 Numpy 数组 img_np = img_tensor.numpy().transpose(0, 2, 3, 1)[0] # 使用 SLIC 算法生成超像素标记图 segments = slic(img_np, n_segments=100, compactness=10) # 可视化超像素标记图 segment_img = mark_boundaries(img_np, segments) # 将 Numpy 数组转换为 PIL 图像 segment_img = Image.fromarray((segment_img * 255).astype(np.uint8)) # 保存超像素标记图 segment_img.save('segments.jpg') n_segments = np.max(segments) + 1 # 初始化超像素块的区域 segment_regions = np.zeros((n_segments, img_np.shape[0], img_np.shape[1])) # 遍历每个超像素块 for i in range(n_segments): # 获取当前超像素块的掩码 mask = (segments == i) # 将当前超像素块的掩码赋值给超像素块的区域 segment_regions[i][mask] = 1 # 保存超像素块的区域 np.save('segment_regions.npy', segment_regions) # 加载超像素块的区域 segment_regions = np.load('segment_regions.npy') # 取出第一个超像素块的区域 segment_region = segment_regions[37] segment_region = (segment_region * 255).astype(np.uint8) # 显示超像素块的区域 plt.imshow(segment_region, cmap='gray') plt.show() # 初始化空白图像 output = np.zeros_like(img_np) # 遍历每个超像素块 for i in range(n_segments): # 获取当前超像素块的掩码 mask = segments == i # 将当前超像素块的掩码赋值给输出图像 output[mask] = segment_regions[i] * 255 # 绘制超像素块的边缘 contours, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(output, contours, -1, (255, 255, 0), 1) # 显示超像素块的区域和边缘 plt.imshow(output) plt.show()上述代码出现问题:ValueError: shape mismatch: value array of shape (500,500) could not be broadcast to indexing result of shape (0,3)
06-07

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值