- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我想从中提取显示三角形的框。我使用简单的垂直和水平线检测来做到这一点,在我的机器上总共需要 10 秒。
现在,由于必须多次执行此操作,因此效率非常重要。那么,openCV(或其他任何地方)中是否有任何方法可以有效地提取这些框?在这里,一种比蛮力方法花费更少时间的有效方法就足够了。
感谢任何帮助!
我的方法:
我创建了一个函数 searchHorizontalLinesX
用于搜索特定长度的行。它通过遍历每个像素一次来实现。我的图片尺寸为:2479 x 3504 = 8686416 像素。 (附加图片质量低,因为上传限制为 2MB。我使用的图片超过 16 MB)
因此,我输入了整个框的宽度 (L1) 和编号为 5 的框的宽度 (L2)。现在,该函数返回具有 L1 长度和 L2 长度的行。因此,所有长度为 L1 的都可以用来提取框 1、2、3、4、6、7、8、9 和 10。
找到这些线后,我会搜索它们之间相差 H 的线,其中 H 是每个框的高度,对于每个框。使用这些我得到了盒子。
对于不是提取的整列的框,我尝试找到一条从顶部到底部的线,然后提取该线相关侧的图像。
def searchHorizontalLinesX(im,lengths,pg,gap=10):
"""
im: PIL image object of the file
lengths: list of lengths of lines to recognize
pg: Page number of the page to take under consideration
"""
im.seek(pg)
dimX = im.size[0]
dimY = im.size[1]
pix = im.load()
line = False
n = len(lengths)
linez = [[] for i in range(0,n)]
for j in range(0,dimY):
for i in range(0,dimX):
if(line):
if(pix[i,j][0]!=0 or pix[i,j][1]!=255):
line = False
end = (i-1,j)
for num,l in enumerate(lengths):
if(end[0]-start[0]>(l-gap) and end[0]-start[0]<(l+gap)):
linez[num].append([start,end])
elif(start[1]==j-1 and i==0):#End to end line
end = (im.size[0],start[1])
line = False
for i,l in enumerate(lengths):
if(end[0]-start[0]>(l-gap) and end[0]-start[0]<(l+gap)):
linez[num].append([start,end])
else:
if(pix[i,j][0]==0 or pix[i,j][1]==255):
start = (i,j)
line = True
return linez
def searchVerticalLines(im,length,pg,gap=5):
"""
im: PIL image object of the file
length: Length of box
dimX: Width of the page
dimY: Height of the page
pg: Page number of the page to take under consideration
"""
im.seek(pg)
dimX = im.size[0]
dimY = im.size[1]
pix = im.load()
line = False
linez = []
start = (0,0)
end = (0,0)
for i in range(0,dimX):
for j in range(0,dimY):
if(line):
if(pix[i,j][0]!=0 or pix[i,j][1]!=255):
line = False
end = (i,j-1)
if(end[1]-start[1]>(length-gap) and end[1]-start[1]<(length+gap)):
linez.append([start,end])
elif(start[0]==i-1 and j==0):
line = False
end = (start[0],im.size[1])
if(end[1]-start[1]>(length-gap) and end[1]-start[1]<(length+gap)):
linez.append([start,end])
else:
if(pix[i,j][0]==0 or pix[i,j][1]==255):
start = (i,j)
line = True
return linez
def grouping(hor,width):
"""
Groups similar horizontal lines together.
hor: List of lines in the format [[(start_x,start_y),(end_x,end_y)],...]
width: What width can a line have. Takes all the lines inside this list into a group
Returns: A list of groups. Each group is a list of lines. Each line has the format [(start_x,start_y),(end_x,end_y)]
"""
horSet = set()
for i in hor:
horSet.add((i[0],i[1]))
group = []
count = 0
for i in hor:
if (i[0],i[1]) in horSet:
print("Visiting :"+str(i))
for j in hor:
if (j[0],j[1]) in horSet:
if(i[0][0]==j[0][0] and i[1][0]==j[1][0] and abs(j[0][1]-i[0][1])<width and abs(j[1][1]-i[1][1])<width):
if(len(group)<=count):
group.append([j])
else:
group[count].append(j)
horSet.remove((j[0],j[1]))
count+=1
return group
def groupingH(ver,width,heightDifference = 2):
"""
Groups similar vertical lines together.
hor: List of lines in the format [[(start_x,start_y),(end_x,end_y)],...]
width: What width can a line have. Takes all the lines inside this list into a group
Returns: A list of groups. Each group is a list of lines. Each line has the format [(start_x,start_y),(end_x,end_y)]
"""
verSet = set()
for i in ver:
verSet.add((i[0],i[1]))
group = []
count = 0
for i in ver:
if (i[0],i[1]) in verSet:
for j in ver:
if (abs(i[0][1]-j[0][1])< heightDifference and abs(i[1][1]-j[1][1])< heightDifference and abs(j[0][0]-i[0][0])<width and abs(j[1][0]-i[1][0])<width):
if(len(group)<=count):
group.append([j])
else:
group[count].append(j)
verSet.remove((j[0],j[1]))
count+=1
return group
def boxing(groupList,boxHeight,gap=5,lw=4):
"""
Given a groupList, it makes a list of coordinates of boxes that have a boxHeight height+-5
"""
boxCoord = []
groupSet = set()
for i in range(len(groupList)):
groupSet.add(i)
for i,g in enumerate(groupList):
if i in groupSet:
print("On :"+str(i))
for j,g1 in enumerate(groupList):
if j in groupSet:
print(" Checking :"+str(j))
if(g[0][0][0]==g1[0][0][0] and g[0][1][0]==g1[0][1][0] and abs(g[len(g)-1][0][1]-g1[0][0][1])>=boxHeight-gap and abs(g[len(g)-1][0][1]-g1[0][0][1])<boxHeight+gap):
groupSet.remove(j)
print(" removing :"+str(j))
boxCoord.append((g[0][0][0]+lw,min(g[len(g)-1][0][1],g1[0][0][1])+1,g[0][1][0]-lw,max(g[len(g)-1][0][1],g1[0][0][1])-1))
break
groupSet.remove(i)
return boxCoord
##############################
def getFrontPageBoxes(im,pg,coords,margin=10):
"""
coords[0]: List of lengths of horizontal lines to be recognized: 0th for box1, 1st for box2+3 (and 4,5,6,7,8,9,10)
coords[1]: Height of box 1
coords[2]: Height of box 2,3
coords[3]: Height of box 4,5,6,7
coords[4]: Height of box 8,10
coords[5]: Height of box 9
"""
# Box 1: Police station... et cetera.
t = []
t1 = t.append(time())
linez = searchHorizontalLinesX(im,coords[0],0) #0 for box 1 <-- Takes time
t2 = t.append(time())
groupForBox1 = grouping(linez[0],4)
leftUpperCorner = groupForBox1[0][len(groupForBox1[0])-1][0]
t3 = t.append(time())
verLinez = searchVerticalLines(im,coords[1],0,10) # <-- Takes time
t4 = t.append(time())
rightLowerCorner = verLinez[0][1]
box1 = im.crop((leftUpperCorner[0]+margin,leftUpperCorner[1]+margin,linez[0][0][1][0]-margin,rightLowerCorner[1]-margin))
# Box 2+3: Polling station name and address
groupForBox2 = grouping(linez[1],4)
bxesFor2 = boxing(groupForBox2,coords[2])
box2Uncropped = im.crop(bxesFor2[len(bxesFor2)-1]) # The last one is the one we want
t5 = t.append(time())
verLinesFor2 = searchVerticalLines(box2Uncropped,box2Uncropped.size[1],0,10) # <-- Takes time
t6 = t.append(time())
group2ForBox2 = groupingH(verLinesFor2,4)
leftUpperCorner = (0,0)
rightLowerCorner = group2ForBox2[0][0][1]
box2 = box2Uncropped.crop((leftUpperCorner[0]+margin,leftUpperCorner[1]+margin,rightLowerCorner[0]-margin,rightLowerCorner[1]-margin))
# Box 4,5,6,7:
groupForBox4 = groupForBox2
bxesFor4 = boxing(groupForBox4,coords[3])
box4Uncropped = im.crop(bxesFor4[0])
t7 = t.append(time())
verLinesFor4 = searchVerticalLines(box4Uncropped,box4Uncropped.size[1],0,10) # <-- Takes time
t8 = t.append(time())
group2ForBox4 = groupingH(verLinesFor4,4)
#There must be 5 groups.
# Error raising mechanism needed here
maleBox = box4Uncropped.crop((group2ForBox4[1][len(group2ForBox4[1])-1][0][0]+margin,0+margin,group2ForBox4[2][0][0][0]-margin,box4Uncropped.size[1]-margin))
femaleBox = box4Uncropped.crop((group2ForBox4[2][len(group2ForBox4[2])-1][0][0]+margin,0+margin,group2ForBox4[3][0][0][0]-margin,box4Uncropped.size[1]-margin))
third_gender = box4Uncropped.crop((group2ForBox4[3][len(group2ForBox4[3])-1][0][0]+margin,0+margin,group2ForBox4[4][0][0][0]-margin,box4Uncropped.size[1]-margin))
total = box4Uncropped.crop((group2ForBox4[4][len(group2ForBox4[4])-1][0][0]+margin,0+margin,box4Uncropped.size[0]-margin,box4Uncropped.size[1]-margin))
# Box 8, 10:
groupForBox8 = groupForBox2
bxesFor8 = boxing(groupForBox8,coords[4])
box8Uncropped = im.crop(bxesFor8[0])
t9 = t.append(time())
verLinesFor8 = searchVerticalLines(box8Uncropped,box8Uncropped.size[1],0,10) # <--Takes time
t10 = t.append(time())
group2ForBox8 = groupingH(verLinesFor8,4)
box10 = box8Uncropped.crop((group2ForBox8[0][len(group2ForBox8)-1][0][0]+margin,0+margin,box8Uncropped.size[0]-margin,box8Uncropped.size[1]-margin))
box8 = box8Uncropped.crop((0+margin,0+margin,group2ForBox8[0][0][0][0]-margin,box8Uncropped.size[1]-margin))
# Box 9:
groupForBox9 = groupForBox2
bxesFor9= boxing(groupForBox9,coords[5])
box9 = im.crop((bxesFor9[0][0]+margin,bxesFor9[0][1]+margin,bxesFor9[0][2]-margin,bxesFor9[0][3]-margin))
for i in range(0,len(t)-1):
print('Time taken :'+str(t[i+1]-t[i]))
return [box1,box2,maleBox,femaleBox,third_gender,total,box8,box9,box10]
def processBoxes(bxLst):
opList = []
for i,box in enumerate(bxLst):
print("box :"+str(i))
opList.append(pt.image_to_string(box,lang='hin+eng',config='--psm 6'))
return opList
def getFrontPageInfo(im,pg,coords):
"""
coords[0]: List of lengths of horizontal lines to be recognized: 0th for box1, 1st for box2+3,
2nd for boxes 4,5,6,7, 3rd for boxes 8 and 10, 4th for box 9
coords[1]: List of lengths of vertical lines to be recognized: 0th for box1
coords[2]: Height of box 2,3
coords[3]: Height of box 4,5,6,7
coords[4]: Height of box 8,10
coords[5]: Height of box 9
"""
boxList = getFrontPageBoxes(im,pg,coords)
return processBoxes(boxList)
最佳答案
查看我的带有注释的代码以获取更多详细信息。我只是做了一个只有 1 盒的 sample 。将同样的方法应用到其他人身上。
import cv2
img = cv2.imread("1.png")
imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
cv2.bitwise_not(thresh,thresh)
im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
#find the document in the image
max_area = 0
max_contour = None
ind = 0
for i,c in enumerate(contours):
area = cv2.contourArea(c)
if area>max_area:
max_area = area
max_contour = c
ind = i
cv2.drawContours(img, contours, ind ,(0,0,255), 2)
#extract the document
rect = cv2.boundingRect(max_contour)
roi = img[rect[1]:rect[1]+rect[3],rect[0]:rect[0]+rect[2]]
(h,w) = roi.shape[:2]
#create a mask (the mask of box 1)
mask1 = (0,0,w*0.88,h*0.062) #the parameter 0.88 and 0.062 were found base on the format of the document
cv2.rectangle(roi,(mask1[0],mask1[1]),(int(mask1[2]),int(mask1[3])),(0,255,0),2)
cv2.imshow("img",img)
cv2.imshow("ROI",roi)
cv2.waitKey()
cv2.destroyAllWindows()
关于image - 使用 openCV 在图像中查找特定框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53323131/
我在 GlassFish (J2EE_1.4) 上的 NetBeans 中开发企业项目。我的项目中有一些实体 bean、一些 session bean 和消息驱动 bean。我以如下方式使用 serv
什么在速度方面更好...... 我正在尝试确定用户是否已将某个 URL 添加到他们的快捷方式列表中。如果他们添加了 URL,页面上就会有一个链接,用于从快捷方式中删除该页面,否则他们可以将其添加到快捷
我的问题如下: 我打开一个Excel-File,但我不知道我的客户在模板文件中使用了哪些可能的标头变量。它们可以是:#DATE,#TIME,#NAME等。因此,我需要查找这些变量,以及是否已使用过:替
我有一堆以“-e”结尾的文件要删除。 $ find . -name "*-e" exec rm {} \; find: exec: unknown primary or operator 正则表达式是
我有一个简单的问题:是否可以在 TypeScript 中获取联合的一部分的类型? 例如,您可以经常使用如下查找类型: interface Person { name: string; } type
我正在尝试设置 Point Cloud Library启用 CUDA 选项的主干构建。 我相信我已经按照 these instructions 正确安装了 CUDA . 在 PCL 构建的 cmake
我将首先说我所知道的唯一 VBA 是操作录制的宏的反复试验。我是一名注册会计师,试图以艰难的方式学习 VBA(并希望我去学校学习计算机编程!)。 我有带有多个工作表的大型工作簿。 G 列中以黄色突出显
当文件数达到阈值时,我试图删除目录中最旧的文件。 list_of_files = os.listdir('log') if len([name for name in list_of_files
我有一个数组,它有一些重复的值。 我必须计算每个重复项的数量及其索引。 打印如: Index of b: 1 Index of b: 4 Index of c: 2 Index of c: 3 Ind
我已经搜索了我的问题的解决方案,但没有成功。热键 ctrl+F 找到的 eclipse 查找/替换功能不起作用。注意:通过 Eclipse 菜单 Edit>Find Replace(不工作我的意思是
我想检查 div 是否包含类为“error”的子级,但条件是错误类显示不等于无。 (意味着错误类必须可见。 如何更改我的以下代码: $(".related_field").each(function
这个问题已经有答案了: 已关闭13 年前。 Possible Duplicate: Can jQuery provide the tag name? 嗨! 这个问题太基础了,我不好意思问,但我尝试了
我一直听说这是 cygwin 的路径问题。它阻止了 emacs 在我的 cygwin 中工作。当我在 cli(不是 bash/cygwin)上执行 find 时,无论我输入什么,我都会得到同样的错误。
我正在使用此变量来获取一个或多个与我需要的值相匹配的值。 var mail = $("#dat").contents().find("td:contains('" + name + "')" ).si
请原谅这个长问题。我只是不确定解决这个问题的最佳方法是什么。 我有一个电子表格(Google 表格),其中包含用户和地址列表,我需要从中创建邮寄标签。该电子表格是从我们的学生信息系统导出的。这些地址应
我正在 Excel VBA 中创建一个公式,以解析单元格中以逗号分隔的“部分”列表。在另一个工作表中查找具有该零件名称的单元格,然后使用找到的该单元格的地址来获取同一行不同列的零件成本。我为此工作了数
我被要求在网络应用程序上实现一些电子邮件地址验证 - 我确信我们都已经经历过一千次了...但是,这一次我被要求在域上进行 MX 查找查看它是否接受电子邮件。 有人知道这样做有任何潜在的问题吗? mx
我有一个切换按钮,可读取.wave文件,并且字符串更改为暂停,然后..... 我的问题是,当用户播放声音时,按钮字符串更改为暂停,结束声音后,该字符串仍为暂停状态,我想将其更改为播放。但是我不知道如何
对于令人困惑的标题提前表示歉意。我的问题如下,我在大约 600 个文件中有以下文本: $_REQUEST['FOO'] 我想将其替换为以下内容: $this->input->post('FOO') 为
我正在使用 Ansible 的查找功能查找 INI 文件中的值。这是文档中的示例: - debug: msg="User in integration is {{ lookup('ini', 'use
我是一名优秀的程序员,十分优秀!