[英]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.