【问题标题】:Recognizing rectangles in template images识别模板图像中的矩形
【发布时间】:2019-01-06 23:26:11
【问题描述】:

所以我试图识别一个已经由边界框定义的区域。示例:

这些图像中这些矩形内的区域有些是白色的,有些是黑色的,而且大部分都是完全不同的大小。这些图像之间唯一的共同特征是红色矩形:

基本上我要做的是创建一个随机生成的 meme 机器人,将随机源图像放置在由这些矩形定义的区域中。我已经拥有大量带有这些红色矩形的预定义区域的图像供使用。我想以某种方式自动化这个过程,目前必须为每个模板定义每个调整大小的形状和偏移量。所以我需要做的是识别矩形内的区域并让它返回定义的调整大小形状和放置源图像所需的偏移量。

我应该怎么做?我应该在 OpenCV 中使用一些东西还是必须训练一个 CNN?只是真的在寻找正确的方向,因为我对解决这个问题的最佳方法非常迷茫。

【问题讨论】:

    标签: python opencv image-processing rectangles


    【解决方案1】:

    我认为 OpenCV 可以做到。以下是您需要的步骤的简短示例。阅读代码中的 cmets 了解更多详情。

    import cv2
    import numpy as np
    
    img = cv2.imread("1.jpg")
    
    #STEP1: get only red color (or the bounding box color) in the image
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    # define range of red color in HSV
    lower_red = np.array([0,50,50])
    upper_red = np.array([0,255,255])
    # Threshold the HSV image to get only blue colors
    mask = cv2.inRange(hsv, lower_red, upper_red)
    red_only = cv2.bitwise_and(img,img, mask= mask)
    
    #STEP2: find contour
    gray_img = cv2.cvtColor(red_only,cv2.COLOR_BGR2GRAY)
    _,thresh = cv2.threshold(gray_img,1,255,cv2.THRESH_BINARY)
    
    _,contours,_ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    
    #max contour in the image is the box you want
    areas = [cv2.contourArea(c) for c in contours]
    sorted_areas = np.sort(areas)
    cnt=contours[areas.index(sorted_areas[-1])]
    r = cv2.boundingRect(cnt)
    cv2.rectangle(img,(r[0],r[1]),(r[0]+r[2],r[1]+r[3]),(0,255,0),3)
    
    cv2.imshow("img",img)
    cv2.imshow("red_only",red_only)
    cv2.imshow("thresh",thresh)
    
    cv2.waitKey()
    cv2.destroyAllWindows()
    

    【讨论】:

      猜你喜欢
      • 2010-12-21
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-22
      • 2014-10-30
      相关资源
      最近更新 更多