我正在将视频分为帧的视频输入。现在,我必须在感兴趣区域的文本上绘制一个矩形。因此,我需要将我在框架上绘制的所有矩形的所有坐标点存储在csv文件中。我需要从每个帧中裁剪所有矩形。 我正在发送用python编写的程序。扩展到这一点,我希望每帧都选择所有矩形。
self.capture = cv2.VideoCapture('ch3_train/Video_2_1_2.mp4')
# Bounding box reference points and boolean if we are extracting coordinates
self.image_coordinates = []
self.extract = False
self.selected_ROI = False
self.update()
def update(self):
while True:
if self.capture.isOpened():
# Read frame
(self.status, self.frame) = self.capture.read()
for i in range(len(self.frame)):
cv2.imshow('image', self.frame)
key = cv2.waitKey(2)
# Crop image
if key == ord('c'):
self.clone = self.frame.copy()
cv2.namedWindow('image')
cv2.setMouseCallback('image', self.extract_coordinates)
while True:
key = cv2.waitKey(2)
cv2.imshow('image', self.clone)
# Crop and display cropped image
if key == ord('c'):
self.crop_ROI()
self.show_cropped_ROI()
# Resume video
if key == ord('r'):
break
# Close program with keyboard 'q'
if key == ord('q'):
cv2.destroyAllWindows()
self.capture.release()
exit(1)
else:
sys.exit()
#pass
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)]
self.extract = True
# Record ending (x,y) coordintes on left mouse bottom release
elif event == cv2.EVENT_LBUTTONUP:
self.image_coordinates.append((x,y))
self.extract = False
self.selected_ROI = True
# (x1,y1,x2,y2)=[int(v) for v in f ]
# Draw rectangle around ROI
cv2.rectangle(self.clone, self.image_coordinates[0], self.image_coordinates[1], (0,255,0), 2)
'''
while self.selected_ROI:
x1 = self.image_coordinates[0][0]
y1 = self.image_coordinates[0][1]
x2 = self.image_coordinates[1][0]
y2 = self.image_coordinates[1][1]
with open ('train_annotations_bbox.csv',mode='w') as bboxfile:
bboxwriter=csv.writer(bboxfile,delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
bboxwriter.writerow(['Xmin','Xmax','Ymin','Ymax'])#[self.image_coordinators[1],self.image_coordinators[0]])
bboxwriter.writerow([x1*0.001,y1*0.001,x2*0.001,y2*0.001])
'''
#for i in event:
# cv2.imwrite("frame%d"+i+".jpg",self.clone)
# Clear drawing boxes on right mouse button click
elif event == cv2.EVENT_RBUTTONDOWN:
self.clone = self.frame.copy()
self.selected_ROI = False
def crop_ROI(self):
if self.selected_ROI:
self.cropped_image = self.frame.copy()
x1 = self.image_coordinates[0][0]
y1 = self.image_coordinates[0][1]
x2 = self.image_coordinates[1][0]
y2 = self.image_coordinates[1][1]
self.cropped_image = self.cropped_image[y1:y2, x1:x2]
print('Cropped image: {} {}'.format(self.image_coordinates[0], self.image_coordinates[1]))
#fromCenter=False
#ROIs=cv2.selectROIs('Select ROIs',self.selected_ROI,fromCenter)
#for i, ctr in enumerate(self.selected_ROI):
# cv2.imshow('roi'+str(i),self.cropped_image)
else:
print('Select ROI to crop before cropping')
def show_cropped_ROI(self):
cv2.imshow('cropped image', self.cropped_image)
我希望输出是在矩形上循环以将其坐标点存储在csv文件中,但实际输出是仅存储csv文件中选择的最后一个矩形。