How to save image to binary format in python?

Question:

I am trying to convert image to binary using python, but something is not working properly. Here is my code:

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

It crashes on the moment of writing an image. Here is the traceback:

Traceback (most recent call last):
  File "D:Pythonprojvenvlibsite-packagesdjangocorehandlersexception.py", line 56, in inner
    response = get_response(request)
  File "D:Pythonprojvenvlibsite-packagesdjangocorehandlersbase.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:Pythonprojsrccoreviews.py", line 48, in create_binary_image
    binarize_image(url)
  File "D:Pythonprojsrccoreutilsimage_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'

Any ideas on what am I doing wrong?
I will be very grateful for anny suggestions!

Answers:

You need to extract the binary image from the tuple before writing it to disk so:


def binarize_image(filename):
    filename = MEDIA_ROOT + "\" + filename
    img = cv2.imread(filename)
    greyscale_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # extract the binary image from the tuple
    _, 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

By using the underscore _ to ignore the first element of the tuple, the binary image can be extracted.

Answered By: Sunderam Dubey
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.