代码之家  ›  专栏  ›  技术社区  ›  Dodeo

cv2.rectangle()在图像上绘制不正确的矩形

  •  0
  • Dodeo  · 技术社区  · 2 年前

    这个想法很简单:用户在某个点P(x,y)点击图像,然后应用程序获取这个坐标,这个坐标决定了正方形的中心。然后这个正方形应该出现在P(x,y)的周围。但我得到的不是形状不合适的矩形。 下面是我的代码。

    创建点击事件: window.fig.canvas.mpl_connect('button_press_event', onclick) ( https://matplotlib.org/stable/users/explain/event_handling.html )

    然后

    frameSize = 64
    ix, iy = 0, 0
    def onclick(event):
        global ix, iy
    
    # take the coordinates of user`s click
        ix, iy = event.xdata, event.ydata
        print (f'Center:\tx = {ix}, y = {iy} frameSize = {frameSize}')
       
    
    #print coordinates
        print ("----------------------")
        left_TOP_x = int(ix - frameSize/2)
        left_TOP_y = int(iy - frameSize/2)
        right_BOTTOM_x = int(ix + frameSize/2)
        right_BOTTOM_y = int(iy + frameSize/2)
        print (f'to int\t left_TOP_x = {left_TOP_x}, left_TOP_y = {left_TOP_y}')
        print (f'to int\t right_BOTTOM_x = {right_BOTTOM_x}, right_BOTTOM_y = {right_BOTTOM_y}')
        print ("----------------------\n")
    
    #draw the square
        cv2.rectangle(img, (left_TOP_x,left_TOP_y,right_BOTTOM_x, right_BOTTOM_y ), color=(255, 0, 0), thickness= 2)
        window.ax.imshow(img)
        window.canvas.draw()
    

    我第一次点击并收到这个:

    (图像大小为254x199) improper rectangle

    但坐标总是很好!

    Center: x = 131.67556141774892, y = 111.16829004329006 frameSize = 64
    ----------------------
    to int   left_TOP_x = 99, left_TOP_y = 79
    to int   right_BOTTOM_x = 163, right_BOTTOM_y = 143
    ----------------------
    

    我通过QtDesigner制作了GUI(也许这很重要)

    self.plotWidget = QtWidgets.QWidget(self.verticalLayoutWidget)
            self.verticalLayout.addWidget(self.plotWidget)
           
            self.plotWidget.setStyleSheet("")
            self.plotWidget.setObjectName("plotWidget")
            self.plotLayout = QtWidgets.QVBoxLayout(self.plotWidget)
            self.plotLayout.setContentsMargins(0, 0, 0, 0)  
            self.plotLayout.setObjectName("plotLayout")
    

    我试着用这个coords裁剪图像。我 get image that I need

     crop_img = img[left_TOP_y:right_BOTTOM_y, left_TOP_x:right_BOTTOM_x]
        crop_img = cv2.cvtColor(crop_img, cv2.COLOR_BGR2RGB)
       
        cv2.imshow("imagggge", crop_img)
        test_image(crop_img)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
    

    但是我还没有解决画正方形的问题。

    1 回复  |  直到 2 年前
        1
  •  1
  •   Cris Luengo    2 年前

    cv2.rectangle 有两种形式:

    cv.rectangle(img, pt1, pt2, color, ...)
    cv.rectangle(img, rec, color, ...)
    

    第一种形式采用左上角和右下角作为描述矩形的参数。第二种形式采用(C++类型) cv::Rect 作为描述矩形的参数。这个 Rect 派生为 (x, y, width, height) 具有 (x, y) 对应于 pt1 以第一种形式。

    所以你的方形绘制线应该是

    cv2.rectangle(img, (left_TOP_x, left_TOP_y, frameSize, frameSize), color=(255, 0, 0), thickness= 2)
    

    cv2.rectangle(img, (left_TOP_x, left_TOP_y), (right_BOTTOM_x, right_BOTTOM_y), color=(255, 0, 0), thickness= 2)