繁体   English   中英

我正在尝试使用 opencv python 库使用 cv2.imwrite() function 将图像保存到文件,但它显示错误

[英]I am trying to save an image to a file by using opencv python library using cv2.imwrite() function but it shows an error

我正在尝试使用cv2.imwrite()使用 OpenCV python 库将图像保存到文件中,但它显示错误。

代码是:

import cv2

# Reading image as gray scale
img = cv2.imread(r'C:\Users\Person\Pictures\Wallpapers (Space)\Carl Sagan.jpg',1)
# saving the image
status = cv2.imwrite(r'C:\Users\Person\Pictures\Wallpapers (Space)\Carl Sagan.jpg',0,img)

print('the status of the image is : ',status)

显示错误:

error                                     Traceback (most recent call last)
<ipython-input-4-773a1fcb9cd4> in <module>
      4 img = cv2.imread(r'C:\Users\Joydeep\Pictures\Wallpapers (Space)\Carl Sagan.jpg',1)
      5 # saving the image
----> 6 status = cv2.imwrite(r'C:\Users\Joydeep\Pictures\Wallpapers (Space)\Carl Sagan.jpg',0,img)
      7 
      8 print('the status of the image is : ',status)

error: OpenCV(4.5.2) :-1: error: (-5:Bad argument) in function 'imwrite'
> Overload resolution failed:
>  - Conversion error: params, what: OpenCV(4.5.2) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-inblc7p7\opencv\modules\core\src\copy.cpp:320: error: (-215:Assertion failed) channels() == CV_MAT_CN(dtype) in function 'cv::Mat::copyTo'
> 
>  - Conversion error: params, what: OpenCV(4.5.2) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-inblc7p7\opencv\modules\core\src\copy.cpp:320: error: (-215:Assertion failed) channels() == CV_MAT_CN(dtype) in function 'cv::Mat::copyTo'
> 

*** 我应该怎么办?

根据文档imwrite具有以下参数:

cv.imwrite( filename, img[, params] )

其中params是指定output的 ImwriteFlags。

所以它可能是0 ,试试:

status = cv2.imwrite(r'C:\Users\Person\Pictures\Wallpapers (Space)\Carl Sagan.jpg',img)

首先,当你使用1作为cv2.imread()方法的第二个参数时,它将以全彩色而不是灰度读取图像; 请注意, 1是标志的默认值。 要将图像作为灰度图像读取,请使用0 ,它是cv2.IMREAD_GRAYSCALE的值。

最后,在编写图像时不要包含0

import cv2

img = cv2.imread(r'C:\Users\Person\Pictures\Wallpapers (Space)\Carl Sagan.jpg', 0)
status = cv2.imwrite(r'C:\Users\Person\Pictures\Wallpapers (Space)\Carl Sagan.jpg', img)

print('the status of the image is : ', status)

如果您更喜欢以彩色方式读取图像,并且只以灰度方式将其写入,您可以使用cv2.cvtColor方法:

import cv2

img = cv2.imread(r'C:\Users\Person\Pictures\Wallpapers (Space)\Carl Sagan.jpg')
status = cv2.imwrite(r'C:\Users\Person\Pictures\Wallpapers (Space)\Carl Sagan.jpg', cv2.cvtColor(img, 6))

print('the status of the image is : ', status)

其中6cv2.COLOR_BGR2GRAY的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM