Cod*_*ist 3 python opencv image image-processing python-imaging-library
所以我试图截取我的显示器的屏幕截图,并且在这样做时只抓取屏幕的一部分。我知道我可以使用 mss 或 opencv、pillow 或任何其他支持边界框的屏幕截图库......但是,不是随机猜测坐标是什么......我的意思是使用边界框坐标截取屏幕截图设置,并查看它是否与我实际尝试拍摄的照片相近。
例如:我的试验坐标是 10,10,500,500 而实际上我需要的实际坐标是 15,40,200,300(这些坐标是组成的)
我解决这个问题的想法是有一个工具,允许我在我需要的图像(屏幕的一部分)周围单击并拖动一个边界框,并让程序返回结果,例如 15,40,200,300。另外,如果我的盒子可以被画出来,那将非常有帮助!如果有另一种方式来实现这一目标,我也会对此持开放态度。
谢谢你。
这个想法是在感兴趣的区域周围单击并拖动一个边界框以获得坐标。为此,我们必须捕获鼠标单击的事件动作并记录 ROI 的开始和结束坐标。OpenCV 允许我们通过处理鼠标点击事件来做到这一点。任何时候触发鼠标单击事件,OpenCV 都会将信息传递给我们的extract_coordinates回调函数。为了处理事件,OpenCV 需要各种参数:
按下左键记录左上角坐标,而释放左键单击记录右下角坐标。然后我们在 ROI 周围绘制一个边界框,并将左上角和右下角矩形区域的坐标打印到控制台。右键单击将重置图像。
提取边界框坐标小部件:
import cv2
class BoundingBoxWidget(object):
def __init__(self):
self.original_image = cv2.imread('1.jpg')
self.clone = self.original_image.copy()
cv2.namedWindow('image')
cv2.setMouseCallback('image', self.extract_coordinates)
# Bounding box reference points
self.image_coordinates = []
def extract_coordinates(self, event, x, y, flags, parameters):
# Record starting (x,y) coordinates on left mouse button click
if event == cv2.EVENT_LBUTTONDOWN:
self.image_coordinates = [(x,y)]
# Record ending (x,y) coordintes on left mouse button release
elif event == cv2.EVENT_LBUTTONUP:
self.image_coordinates.append((x,y))
print('top left: {}, bottom right: {}'.format(self.image_coordinates[0], self.image_coordinates[1]))
print('x,y,w,h : ({}, {}, {}, {})'.format(self.image_coordinates[0][0], self.image_coordinates[0][1], self.image_coordinates[1][0] - self.image_coordinates[0][0], self.image_coordinates[1][1] - self.image_coordinates[0][1]))
# Draw rectangle
cv2.rectangle(self.clone, self.image_coordinates[0], self.image_coordinates[1], (36,255,12), 2)
cv2.imshow("image", self.clone)
# Clear drawing boxes on right mouse button click
elif event == cv2.EVENT_RBUTTONDOWN:
self.clone = self.original_image.copy()
def show_image(self):
return self.clone
if __name__ == '__main__':
boundingbox_widget = BoundingBoxWidget()
while True:
cv2.imshow('image', boundingbox_widget.show_image())
key = cv2.waitKey(1)
# Close program with keyboard 'q'
if key == ord('q'):
cv2.destroyAllWindows()
exit(1)
Run Code Online (Sandbox Code Playgroud)