如何将OpenCV NumPy数组转为Wand Image格式并保存二值化图像
Hey there! Let's tackle converting that OpenCV-processed NumPy array back to a Wand Image so you can save it properly. Here's how to make it work seamlessly with your existing workflow:
First, let's align with your current pipeline: you're generating a NumPy array from a blob, running it through your binarize_image function to get a binary ndarray, and now need to convert that back to Wand's Image format for saving.
Complete Solution Code
Here's the adjusted code flow including the critical conversion step:
import cv2 import numpy as np from wand.image import Image import os # Make sure your threshold constant is defined (example value shown) BINARY_THREHOLD = 127 def binarize_image(img): ret1, th1 = cv2.threshold(img, BINARY_THREHOLD, 255, cv2.THRESH_BINARY) return th1 # --- Your existing setup --- # blob = make_blob(...) # Raw JPEG buffer from your make_blob function # img_np = np.frombuffer(blob, dtype=np.uint8) # img_cv = cv2.imdecode(img_np, cv2.IMREAD_GRAYSCALE) # Load as grayscale # After running binarization binary_img_np = binarize_image(img_cv) # --- Convert OpenCV ndarray to Wand Image --- with Image( blob=binary_img_np.tobytes(), width=binary_img_np.shape[1], height=binary_img_np.shape[0], format='gray' # Specify single-channel grayscale format ) as wand_img: # Save using your original path logic output_path = os.path.join(pdf_folder, image_folder, outputFileName) wand_img.save(filename=output_path)
Key Details to Note
- NumPy to Raw Bytes: Your binary ndarray is a 2D array of
uint8values (0 or 255 for binary images). Using.tobytes()converts this array into a raw byte stream that Wand can parse directly. - Wand Image Setup: We pass the raw bytes via the
blobparameter, then set the exact dimensions (remember: OpenCV uses(height, width)for array shape, so we flip those for Wand'swidth/heightparams). Theformat='gray'flag tells Wand this is a single-channel grayscale image, which matches your binary output. - Context Manager: Using
withensures the Wand Image resource is cleaned up automatically after saving, which is a good practice to avoid memory leaks.
Quick Validation Checks
- Confirm your
binary_img_npis a 2D array (no extra color channels). If you loaded the original image as BGR (3-channel),cv2.thresholdstill works, but double-check to avoid unexpected formatting issues. - Ensure
BINARY_THREHOLDis properly defined in your code (the example value above is just a placeholder—use your actual threshold value).
That should get your image saved correctly in Wand's format without a hitch! 😊
内容的提问来源于stack exchange,提问作者Anee
相关产品推荐
相关产品推荐

