我试图通过使用cv2.imwrite()函数使用opencv python库将图像保存到文件中,但它显示了一个错误

2024-04-24 07:56:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用opencvpython库使用cv2.imwrite()将图像保存到文件中,但它显示了一个错误

代码是:

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'
> 

***我该怎么办


Tags: theinimageimgstatusspaceerrorcv2
2条回答

首先,当使用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的值

根据docsimwrite具有以下参数:

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

其中params是指定输出的ImwriteFlags

所以可能是0,试试:

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

相关问题 更多 >