我正在尝试使用python将图像转换为二进制,但有些东西无法正常工作。以下是我的代码:
def binarize_image(filename):
filename = MEDIA_ROOT + "\\" + filename
img = cv2.imread(filename)
greyscale_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
binary_img = cv2.threshold(greyscale_img, 127, 64, cv2.THRESH_BINARY,)
resized_name = f"binary_{filename[:len(filename) - 4]}.png"
cv2.imwrite(resized_name, binary_img)
return resized_name
它在写入图像时崩溃,回溯如下:
Traceback (most recent call last):
File "D:\Python\proj\venv\lib\site-packages\django\core\handlers\exception.py", line 56, in inner
response = get_response(request)
File "D:\Python\proj\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Python\proj\src\core\views.py", line 48, in create_binary_image
binarize_image(url)
File "D:\Python\proj\src\core\utils\image_binarize.py", line 17, in binarize_image
cv2.imwrite(resized_name, binary_img)
cv2.error: OpenCV(4.7.0) :-1: error: (-5:Bad argument) in function 'imwrite'
> Overload resolution failed:
> - img is not a numerical tuple
> - Expected Ptr<cv::UMat> for argument 'img'
你知道我做错了什么吗?我将非常感谢你的建议!
1条答案
按热度按时间0qx6xfy61#
您需要在将二进制映像写入磁盘之前从元组中提取它,因此:
通过使用下划线
_
来忽略元组的第一个元素,可以提取二值图像。