我正在搞混opencv2进行神经样式转换...在cv2.imshow(“ Output”,output)中,我可以说出我的照片。但是,当我使用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,之前的所有行都试图修改输出图片。
答案 0 :(得分:3)
变量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)