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

xcitsw88  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(115)

这个想法很简单:用户点击图像上的某个点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()

我第一次点击并收到这个:
(图片大小为254 x199)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")

我已经试着用这个坐标裁剪图像。我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()

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

zmeyuzjn

zmeyuzjn1#

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)

相关问题