提取边界框并将其另存为图像 [英] Extract bounding box and save it as an image
本文介绍了提取边界框并将其另存为图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设您有以下图片:
现在,我想将每个独立字母提取到单独的图像中.目前,我已经恢复了轮廓,然后绘制了一个边框,在本例中为字符a
:
Now I want to extract each of the independent letters into individual images. Currently, I've recovered the contours and then drew a bounding box, in this case for the character a
:
的边框
此后,我要提取每个框(在本例中为字母a
)并将其保存到图像文件中.
After this, I want to extract each of the boxes (in this case for the letter a
) and save it to an image file.
预期结果:
到目前为止,这是我的代码:
Here's my code so far:
import numpy as np
import cv2
im = cv2.imread('abcd.png')
im[im == 255] = 1
im[im == 0] = 255
im[im == 1] = 0
im2 = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(im2,127,255,0)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for i in range(0, len(contours)):
if (i % 2 == 0):
cnt = contours[i]
#mask = np.zeros(im2.shape,np.uint8)
#cv2.drawContours(mask,[cnt],0,255,-1)
x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
cv2.imshow('Features', im)
cv2.imwrite(str(i)+'.png', im)
cv2.destroyAllWindows()
提前谢谢.
推荐答案
以下内容将给您一个字母
The following will give you a single letter
letter = im[y:y+h,x:x+w]
这篇关于提取边界框并将其另存为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文