如何用OpenCV读取WordDetector裁剪的图像数组并转灰度?
字符分割:直接处理WordDetector裁剪的内存图像数组
我正在进行字符分割,使用WordDetector通过以下代码裁剪单词图像:
def contours_words(image_file): im3 = image_file.copy() img = prepare_img(image_file, 50) detections = detect(img, kernel_size=25, sigma=3, theta=8, min_area=100) line = sort_line(detections)[0] for i, word in enumerate(line): if word.bbox.h > 19 and word.bbox.w >= 22 and word.bbox.w <= 250: contours_letters(word.img)
得到裁剪后的图像数组后,我需要用OpenCV将其转为灰度图并进行轮廓检测,预期代码如下:
gray = cv2.cvtColor(image_file, cv2.COLOR_BGR2GRAY) ret, thresh1 = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV) dilated = cv2.dilate(thresh1, None, iterations=1) cnts = cv2.findContours( dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) cnts = sort_contours(cnts, method="left-to-right")[0]
但使用image = cv2.imread(image_file)读取该图像数组时出现错误,且我不想先保存图像再重新读取,求助解决方法。
解决方案
问题出在对cv2.imread的误用:这个函数仅用于读取磁盘上的图像文件路径,不能直接读取内存中的图像数组。而word.img本身就是WordDetector裁剪后返回的内存图像数组,直接传入OpenCV处理流程即可。
修改后的contours_letters函数示例:
def contours_letters(word_img): # 先判断图像是否为彩色图(三通道),再决定是否转灰度 if len(word_img.shape) == 3: # 若为BGR格式彩色图,转换为灰度图 gray = cv2.cvtColor(word_img, cv2.COLOR_BGR2GRAY) else: # 已经是单通道灰度图,直接使用 gray = word_img ret, thresh1 = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV) dilated = cv2.dilate(thresh1, None, iterations=1) cnts = cv2.findContours( dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) cnts = sort_contours(cnts, method="left-to-right")[0] # 这里添加后续轮廓处理逻辑,比如提取单个字符等
关键说明
word.img是内存中的图像矩阵,无需存盘再读取,直接作为参数传入处理函数即可。- 注意图像通道数:通过
len(word_img.shape)判断,结果为3表示三通道彩色图,结果为2表示单通道灰度图,避免不必要的格式转换报错。
内容的提问来源于stack exchange,提问作者Emad Uones
相关产品推荐
相关产品推荐

