【问题标题】:How to save an image having use Otsu's filter如何保存使用 Otsu 过滤器的图像
【发布时间】:2021-01-07 13:04:18
【问题描述】:

好吧,我对应用此过滤器应使用的文件格式以及保存图像应使用的文件格式有点困惑。

这是我的代码

img1 = cv2.imread('I1_fil2D.png',1)
skdemo.imshow_with_histogram(img1);

from skimage.filters import threshold_otsu
thresh = threshold_otsu(rgb2gray(img1))
bw_img1 = rgb2gray(img1) > thresh

plt.imshow(bw_img1)

我使用了rgb2gray() 命令,因为threshold_otsu() 需要灰度图像作为输入。我尝试使用cv2.imwrite('bw1.jpg',bw_img1),但它显示:TypeError: Expected Ptr<cv::UMat> for argument 'img'(我也在此命令之前尝试了bw_img1 = np.array(bw_img1),但没有任何改变)。此外,我尝试了imsave,但它也不起作用,因为我使用了cv2 进行阈值处理。

【问题讨论】:

    标签: python python-3.x image image-processing


    【解决方案1】:

    您的代码有问题,这就是cv2.imwrite() 无法保存图像的原因。

    当您执行bw_img1 = rgb2gray(img1) > thresh 时,输出是一个真/假矩阵,因为它不是数字cv2.imwrite() 不会保存它。

    记住,cv2.imread() 将 RGB 图像读取为 BGR,所以我更正了它。

    我修复了代码,现在它可以工作了。

    import cv2
    import numpy as np
    import matplotlib.pyplot as plt
    from skimage.filters import threshold_otsu
    
    img1 = cv2.imread('myimage.png',1)
    
    #image from BGR to GRAYSCALE
    gray_image = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
    
    #get the threshold
    thresh = threshold_otsu(gray_image)
    #create a copy of the gray image
    bw_img1 = np.copy(gray_image)
    #apply the binarization
    bw_img1[bw_img1 < thresh] = 0
    bw_img1[bw_img1 >= thresh] = 255
    
    plt.imshow(bw_img1)
    
    cv2.imwrite("otsu.png", bw_img1)
    

    【讨论】:

    • 如果对您有帮助,能否标记为正确答案,谢谢。
    猜你喜欢
    • 2013-03-18
    • 1970-01-01
    • 2017-02-12
    • 2015-08-05
    • 2017-11-29
    相关资源
    最近更新 更多