0

How can I convert the numpy array got from binarize_image function and save that image. I am doing pre-processing on images. After converting the image into grayscale, I had used the turned them into binary image.

def binarize_image(img):
    ret1, th1 = cv2.threshold(img, BINARY_THREHOLD, 255, cv2.THRESH_BINARY)
    return th1 # numpy.ndarray

Here i am saving the image

   img.format = 'jpeg'
img_buffer = np.asarray(bytearray(img.make_blob()), dtype=np.uint8)
img = binarize_image(img_buffer)

# ..... Code to convert the ndarray back to Wand Image format .......

img.save(filename=os.path.join(pdf_folder,image_folder,outputFileName))
Anee
  • 35
  • 1
  • 8

1 Answers1

1

You're confusing an image file with pixel data buffer. Simply decode the JPEG blob to a Mat, then encoded back.

def binarize_image(img):
    mat = cv2.imdecode(img, cv2.IMREAD_UNCHANGED)
    ret1, th1 = cv2.threshold(mat, 127, 255, cv2.THRESH_BINARY)
    return cv2.imencode(".jpg", th1)

with Image(filename="wizard:") as img:
    img_buffer = np.asarray(bytearray(img.make_blob("JPEG")), dtype=np.uint8)
    ret, mat = binarize_image(img_buffer)
    with Image(blob=mat) as timg:
        timg.save(filename="output.jpg")

output.jpg

Although you could achieve the same task directly with by using either Image.threshold, Image.contrast_stretch, Image.level, or Image.quantize methods.

emcconville
  • 23,800
  • 4
  • 50
  • 66