代码之家  ›  专栏  ›  技术社区  ›  Acy

OpenCV2 IMWRITE正在写入黑色图像

  •  -1
  • Acy  · 技术社区  · 7 年前

    我正在和OpenCV2纠缠不清的神经系统转移…在cv2.imshow(“输出”,输出)中,我可以说出我的图片。但当我用cv2.imwrite将输出写入文件时(“my_file.jpg”,输出)。是因为我的文件扩展名错误吗?但是,当我确实喜欢cv2.imwrite(“my_file.jpg”,input)时,它会显示我的原始输入图片。有什么想法吗?提前谢谢。

    # import the necessary packages
    from __future__ import print_function
    import argparse
    
    import time
    import cv2
    import imutils
    
    import numpy as np
    from imutils.video import VideoStream
    
    # construct the argument parser and parse the arguments
    ap = argparse.ArgumentParser()
    ap.add_argument("-m", "--model", required=True,
        help="neural style transfer model")
    ap.add_argument("-i", "--image", required=True,
        help="input image to apply neural style transfer to")
    
    args = vars(ap.parse_args())
    
    # load the neural style transfer model from disk
    print("[INFO] loading style transfer model")
    net = cv2.dnn.readNetFromTorch(args["model"])
    
    # load the input image, resize it to have a width of 600 pixels, and
    # then grab the image dimensions
    image = cv2.imread(args["image"])
    image = imutils.resize(image, width=600)
    (h, w) = image.shape[:2]
    
    # construct a blob from the image, set the input, and then perform a
    # forward pass of the network
    blob = cv2.dnn.blobFromImage(image, 1.0, (w, h),
        (103.939, 116.779, 123.680), swapRB=False, crop=False)
    net.setInput(blob)
    start = time.time()
    output = net.forward()
    end = time.time()
    
    # reshape the output tensor, add back in the mean subtraction, and
    # then swap the channel ordering
    output = output.reshape((3, output.shape[2], output.shape[3]))
    output[0] += 103.939
    output[1] += 116.779
    output[2] += 123.680
    output /= 255.0
    output = output.transpose(1, 2, 0)
    
    # show information on how long inference took
    print("[INFO] neural style transfer took {:.4f} seconds".format(
        end - start))
    
    # show the images
    cv2.imshow("Input", image)
    cv2.imshow("Output", output)
    cv2.waitKey(0)
    cv2.imwrite("dogey.jpg", output)
    

    只有最后4行代码必须处理imshow和imwrite,所有行在尝试修改输出图片之前。

    1 回复  |  直到 7 年前
        1
  •  3
  •   Max Kapsecker    7 年前

    变量 output 表示由像素组成的彩色图像。每个像素由三个值(RGB)决定。根据图像的表示,每个值都可以从离散范围[0,255]或连续范围[0,1]中选择。但是,在下面的代码行中,您正在缩放 输出 从离散范围[0255]到“连续”范围[0,1]。

    output /= 255.0
    

    而函数 cv2.imshow(...) 可以处理使用范围[0,1]中的浮点值存储的图像 cv2.imwrite(...) 函数不能。您必须传递由范围[0,255]内的值组成的图像。在您的例子中,您传递的值都接近于零,并且远离255。因此,假设图像为无色,因此为黑色。快速解决方法可能是:

    cv2.imwrite("dogey.jpg", 255*output)