OpenCV2的imwrite函数正在写入一张黑色图片。

8
我正在使用OpenCV2进行神经风格转移实验... 在cv2.imshow("Output", output)中,我能够看到我的图片。但是当我用cv2.imwrite("my_file.jpg", output)将输出写入文件时,为什么会出现问题?这是因为我的文件扩展名不正确吗?然而,当我像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
一堆可能的重复问题:https://stackoverflow.com/search?q=imwrite+black - Dan Mašek
1个回答

33

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

output /= 255.0

虽然cv2.imshow(...)函数可以处理范围在[0, 1]内的浮点值存储的图像,但cv2.imwrite(...)函数不能。您必须传递一个由范围在[0, 255]内的值组成的图像。在您的情况下,您正在传递接近零且离255“远”的值。因此,图像被认为是无色的,因此为黑色。一个快速的解决方法可能是:

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

6
非常好的、简单明了的解释!谢谢!Stack Overflow 不喜欢我只添加评论表示感谢,但我仍然要感谢你! - Acy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接