删除不需要的宽高比框

时间:2014-09-08 18:58:44

标签: python opencv

现在我正在学习python opencv尤其是来自http://opencvpython.blogspot.com我在使用查找轮廓功能和边界矩形功能后找到车牌时遇到此问题,例如我在前窗有3-5个盒子,背景树等等。任何人都可以帮助我,因为我很努力地找到答案。并确定我已经使用了许多预处理,如:

  1. 灰度
  2. 阈值
  3. 形态
  4. 我的代码:

    import cv2
    import numpy as np
    
    #import image
    im = cv2.imread('sample_1.jpg')
    #convert to grayscale
    gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
    #apply bilateral filter 
    gray = cv2.bilateralFilter(gray,11,17,17)
    #preparing a kernel matrix 5x5
    kernel = np.ones((5,5),np.uint8)
    #tophat ops
    cv2.morphologyEx(gray,cv2.MORPH_TOPHAT, kernel)
    edged = cv2.Canny(tophat,30,200)
    dilated = cv2.dilate(edged,kernel,iterations = 3)
    #finding contour
    (cnts,_) = cv2.findContours(edged,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    cnts = sorted(cnts, key = cv2.contourArea, reverse = True)
    screenCnt = None
    for c in cnts:
        peri = cv2.arcLength(c,True)
        approx = cv2.approxPolyDP(c,0.02*peri,True)
        x,y,w,h = cv2.boundingRect(c)
        print cv2.contourArea(c)
        x,y,w,h = cv2.boundingrect(c)
        cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),3)
        roi = im[y:y+h, x:x+w]
        cv2.imwrite(roi.png',roi)
        if len (approx)==4
            screenCnt = approx
            break
    cv2.imshow("test",im)
    cv2.waitKey(0)
    

    代码主要来自浏览和阅读博客。重点是这个代码我在车牌上有多个方框。我想要的只是车牌,裁剪它然后进行一些字符分割。

1 个答案:

答案 0 :(得分:0)

import cv2
import numpy as np
#import image
im = cv2.imread('sample_1.jpg')
#convert to grayscale
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
#apply bilateral filter 
gray = cv2.bilateralFilter(gray,11,17,17)
#preparing a kernel matrix 5x5
kernel = np.ones((5,5),np.uint8)
#tophat ops
cv2.morphologyEx(gray,cv2.MORPH_TOPHAT, kernel)
edged = cv2.Canny(tophat,30,200)
dilated = cv2.dilate(edged,kernel,iterations = 3)
#finding contour
(cnts,_) = cv2.findContours(edged,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)
screenCnt = None
for c in cnts:
    peri = cv2.arcLength(c,True)
    approx = cv2.approxPolyDP(c,0.02*peri,True)
    x,y,w,h = cv2.boundingRect(c)
    print cv2.contourArea(c)
    x,y,w,h = cv2.boundingrect(c)
    cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),3)
    roi = im[y:y+h, x:x+w]
    cv2.imwrite(roi.png',roi)
    if len (approx)==4
        screenCnt = approx
        break
cv2.imshow("test",im)
cv2.waitKey(0)