[英]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'
>
*** 我应该怎么办?
首先,当你使用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)
其中6
是cv2.COLOR_BGR2GRAY
的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.