MCPcopy
hub / github.com/sml2h3/ddddocr / binarize_image

Method binarize_image

ddddocr/preprocessing/image_processor.py:200–238  ·  view source on GitHub ↗

图像二值化 Args: image: 输入图像 threshold: 二值化阈值 method: 二值化方法 ('simple', 'otsu', 'adaptive') Returns: 二值化后的图像 Raises: ImageProcessError: 当处理失败时

(image: Image.Image, threshold: int = 128, 
                      method: str = 'simple')

Source from the content-addressed store, hash-verified

198
199 @staticmethod
200 def binarize_image(image: Image.Image, threshold: int = 128,
201 method: str = 'simple') -> Image.Image:
202 """
203 图像二值化
204
205 Args:
206 image: 输入图像
207 threshold: 二值化阈值
208 method: 二值化方法 ('simple', 'otsu', 'adaptive')
209
210 Returns:
211 二值化后的图像
212
213 Raises:
214 ImageProcessError: 当处理失败时
215 """
216 try:
217 # 转换为灰度图
218 if image.mode != 'L':
219 gray_image = image.convert('L')
220 else:
221 gray_image = image
222
223 img_array = image_to_numpy(gray_image)
224
225 if method == 'simple':
226 _, binary = cv2.threshold(img_array, threshold, 255, cv2.THRESH_BINARY)
227 elif method == 'otsu':
228 _, binary = cv2.threshold(img_array, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
229 elif method == 'adaptive':
230 binary = cv2.adaptiveThreshold(img_array, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
231 cv2.THRESH_BINARY, 11, 2)
232 else:
233 raise ValueError(f"不支持的二值化方法: {method}")
234
235 return numpy_to_image(binary, 'L')
236
237 except Exception as e:
238 raise ImageProcessError(f"图像二值化失败: {str(e)}") from e
239
240 @staticmethod
241 def preprocess_for_ocr(image: Image.Image, target_height: int = 64,

Callers

nothing calls this directly

Calls 3

image_to_numpyFunction · 0.85
numpy_to_imageFunction · 0.85
ImageProcessErrorClass · 0.85

Tested by

no test coverage detected