Ipython cv2.imwrite() 不保存图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40136070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ipython cv2.imwrite() not saving image
提问by Niladri Chakraborty
I have written a code in python opencv. I am trying to write the processed image back to disk but the image is not getting saved and it is not showing any error(runtime and compilation) The code is
我在 python opencv 中写了一段代码。我正在尝试将处理后的图像写回磁盘,但图像没有被保存,也没有显示任何错误(运行时和编译)代码是
"""
Created on Wed Oct 19 18:07:34 2016
@author: Niladri
"""
import numpy as np
import cv2
if __name__ == '__main__':
import sys
img = cv2.imread('C:\Users\Niladri\Desktop\TexturesCom_LandscapeTropical0080_2_S.jpg')
if img is None:
print 'Failed to load image file:'
sys.exit(1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
h, w = img.shape[:2]
eigen = cv2.cornerEigenValsAndVecs(gray, 15, 3)
eigen = eigen.reshape(h, w, 3, 2) # [[e1, e2], v1, v2]
#flow = eigen[:,:,2]
iter_n = 10
sigma = 5
str_sigma = 3*sigma
blend = 0.5
img2 = img
for i in xrange(iter_n):
print i,
gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
eigen = cv2.cornerEigenValsAndVecs(gray, str_sigma, 3)
eigen = eigen.reshape(h, w, 3, 2) # [[e1, e2], v1, v2]
x, y = eigen[:,:,1,0], eigen[:,:,1,1]
print eigen
gxx = cv2.Sobel(gray, cv2.CV_32F, 2, 0, ksize=sigma)
gxy = cv2.Sobel(gray, cv2.CV_32F, 1, 1, ksize=sigma)
gyy = cv2.Sobel(gray, cv2.CV_32F, 0, 2, ksize=sigma)
gvv = x*x*gxx + 2*x*y*gxy + y*y*gyy
m = gvv < 0
ero = cv2.erode(img, None)
dil = cv2.dilate(img, None)
img1 = ero
img1[m] = dil[m]
img2 = np.uint8(img2*(1.0 - blend) + img1*blend)
#print 'done'
cv2.imshow('dst_rt', img2)
cv2.waitKey(0)
cv2.destroyAllWindows()
#cv2.imwrite('C:\Users\Niladri\Desktop\leaf_image_shock_filtered.jpg', img2)
for i in xrange(iter_n):
print i,
gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
eigen = cv2.cornerEigenValsAndVecs(gray, str_sigma, 3)
eigen = eigen.reshape(h, w, 3, 2) # [[e1, e2], v1, v2]
x, y = eigen[:,:,1,0], eigen[:,:,1,1]
print eigen
gxx = cv2.Sobel(gray, cv2.CV_32F, 2, 0, ksize=sigma)
gxy = cv2.Sobel(gray, cv2.CV_32F, 1, 1, ksize=sigma)
gyy = cv2.Sobel(gray, cv2.CV_32F, 0, 2, ksize=sigma)
gvv = x*x*gxx + 2*x*y*gxy + y*y*gyy
m = gvv < 0
ero = cv2.erode(img, None)
dil = cv2.dilate(img, None)
img1 = dil
img1[m] = ero[m]
img2 = np.uint8(img2*(1.0 - blend) + img1*blend)
print 'done'
#cv2.imwrite('D:\IP\tropical_image_sig5.bmp', img2)
cv2.imshow('dst_rt', img2)
cv2.waitKey(0)
cv2.destroyAllWindows()
#cv2.imshow('dst_rt', img2)
cv2.imwrite('C:\Users\Niladri\Desktop\tropical_image_sig5.bmp', img2)
Can anyone please tell me why it is not working. cv2.imshow is working properly(as it is showing the correct image). Thanks and Regards Niladri
谁能告诉我为什么它不起作用。cv2.imshow 工作正常(因为它显示了正确的图像)。感谢和问候 Niladri
回答by Jean-Fran?ois Fabre
As a general and absolute rule, you haveto protect your windows path strings (containing backslashes) with r
prefix or some characters are interpreted (ex: \n,\b,\v,\x
aaaaand \t
, full list here):
作为一般和绝对规则,您必须使用r
前缀或解释某些字符来保护您的 Windows 路径字符串(包含反斜杠)(例如:\n,\b,\v,\x
aaaaand \t
,完整列表在这里):
so when doing this:
所以当这样做时:
cv2.imwrite('C:\Users\Niladri\Desktop\tropical_image_sig5.bmp', img2)
you're trying to save to C:\Users\Niladri\Desktop<TAB>ropical_image_sig5.bmp
你试图保存到 C:\Users\Niladri\Desktop<TAB>ropical_image_sig5.bmp
And the annoying thing with imread
and imwrite
is that those functions don't throw exceptions on errors, but fail silently. imwrite
returns False
而伴随着恼人的事情imread
,并imwrite
为那些功能不扔在错误的异常,只是默默地失败。imwrite
返回False
>>> cv2.imread("D:/nonexisting.jpg") # this returns None, no error
>>> s = cv2.imread("D:/sloth_book.jpg") # this works
>>> s
array([[[250, 250, 250],
[246, 246, 246],
[255, 255, 255],
...,
>>> cv2.imwrite("inexistent_dir/file.jpg",s) # dir doesn't exist, write fails
False
So you have to check return value of those functions.
所以你必须检查这些函数的返回值。
Do this:
做这个:
if not cv2.imwrite(r'C:\Users\Niladri\Desktop\tropical_image_sig5.bmp', img2):
raise Exception("Could not write image")
Note: the read works fine because "escaped" uppercase letters have no particular meaning in python 2 (\U
and \N
have a meaning in python 3 so it wouldn't have worked)
注意:读取工作正常,因为“转义”大写字母在 python 2 中没有特殊含义(\U
并且\N
在 python 3 中具有含义,因此它不会起作用)
And if there's an error, the program now complains loudly.
如果出现错误,程序现在会大声抱怨。
回答by R. S. Nikhil Krishna
As Jean suggested, the error is due to the \ being interpretted as an escape sequence. It is hence always safer to use os.path.join()
as it is more cross platform and you need not worry about the escape sequence problem. For instance, in your case, you further need not worry about the first few arguments, as that is your home directory
正如 Jean 所建议的,错误是由于 \ 被解释为转义序列。因此使用os.path.join()
它总是更安全,因为它更跨平台,您不必担心转义序列问题。例如,在您的情况下,您无需担心前几个参数,因为那是您的主目录
import os
cv2.imwrite(os.path.join(os.path.expanduser('~'),'Desktop','tropical_image_sig5.bmp'), img2)
os.path.expanduser('~')
will directly return your home directory.
os.path.expanduser('~')
将直接返回您的主目录。
回答by Jeff Blumenthal
If you want to have the paths in your code portable, look into pathlib.
如果您希望代码中的路径可移植,请查看 pathlib。