You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
classresizeImage(object):
""" If either the width or height of an image exceed a specified value, resize the image so that: 1. The maximum of the new height and new width does not exceed a specified value 2. The new height and new width are divisible by 8 3. The aspect ratio is preserved No resizing is done if both height and width are smaller than the specified value By: Minh Hoai Nguyen ([email protected]) """def__init__(self, MAX_HW=1504):
self.max_hw=MAX_HWdef__call__(self, sample):
image,lines_boxes=sample['image'], sample['lines_boxes']
W, H=image.sizeifW>self.max_hworH>self.max_hw:
scale_factor=float(self.max_hw)/max(H, W)
new_H=8*int(H*scale_factor/8)
new_W=8*int(W*scale_factor/8)
resized_image=transforms.Resize((new_H, new_W))(image)
else:
scale_factor=1resized_image=imageboxes=list()
forboxinlines_boxes:
box2= [int(k*scale_factor) forkinbox]
y1, x1, y2, x2=box2[0], box2[1], box2[2], box2[3]
boxes.append([0, y1,x1,y2,x2])
boxes=torch.Tensor(boxes).unsqueeze(0)
resized_image=Normalize(resized_image)
sample= {'image':resized_image,'boxes':boxes}
returnsample
classresizeImageWithGT(object):
""" If either the width or height of an image exceed a specified value, resize the image so that: 1. The maximum of the new height and new width does not exceed a specified value 2. The new height and new width are divisible by 8 3. The aspect ratio is preserved No resizing is done if both height and width are smaller than the specified value By: Minh Hoai Nguyen ([email protected]) Modified by: Viresh """def__init__(self, MAX_HW=1504):
self.max_hw=MAX_HWdef__call__(self, sample):
image,lines_boxes,density=sample['image'], sample['lines_boxes'],sample['gt_density']
W, H=image.sizeifW>self.max_hworH>self.max_hw:
scale_factor=float(self.max_hw)/max(H, W)
new_H=8*int(H*scale_factor/8)
new_W=8*int(W*scale_factor/8)
resized_image=transforms.Resize((new_H, new_W))(image)
resized_density=cv2.resize(density, (new_W, new_H))
orig_count=np.sum(density)
new_count=np.sum(resized_density)
ifnew_count>0: resized_density=resized_density* (orig_count/new_count)
else:
scale_factor=1resized_image=imageresized_density=densityboxes=list()
forboxinlines_boxes:
box2= [int(k*scale_factor) forkinbox]
y1, x1, y2, x2=box2[0], box2[1], box2[2], box2[3]
boxes.append([0, y1,x1,y2,x2])
boxes=torch.Tensor(boxes).unsqueeze(0)
resized_image=Normalize(resized_image)
resized_density=torch.from_numpy(resized_density).unsqueeze(0).unsqueeze(0)
sample= {'image':resized_image,'boxes':boxes,'gt_density':resized_density}
returnsample
defselect_exemplar_rois(image):
all_rois= []
print("Press 'q' or Esc to quit. Press 'n' and then use mouse drag to draw a new examplar, 'space' to save.")
whileTrue:
key=cv2.waitKey(1) &0xFFifkey==27orkey==ord('q'):
breakelifkey==ord('n') orkey=='\r':
rect=cv2.selectROI("image", image, False, False)
x1=rect[0]
y1=rect[1]
x2=x1+rect[2] -1y2=y1+rect[3] -1all_rois.append([y1, x1, y2, x2])
forrectinall_rois:
y1, x1, y2, x2=rectcv2.rectangle(image, (x1, y1), (x2, y2), (255, 0, 0), 2)
print("Press q or Esc to quit. Press 'n' and then use mouse drag to draw a new examplar")
returnall_rois
Feature Correlation + Density Prediction + Adaptation
withtorch.no_grad():
features=extract_features(resnet50_conv, image.unsqueeze(0), boxes.unsqueeze(0), MAPS, Scales)
ifnotargs.adapt:
withtorch.no_grad(): output=regressor(features)
else:
features.required_grad=True#adapted_regressor = copy.deepcopy(regressor)adapted_regressor=regressoradapted_regressor.train()
optimizer=optim.Adam(adapted_regressor.parameters(), lr=args.learning_rate)
pbar=tqdm(range(args.gradient_steps))
forstepinpbar:
optimizer.zero_grad()
output=adapted_regressor(features)
lCount=args.weight_mincount*MincountLoss(output, boxes, use_gpu=use_gpu)
lPerturbation=args.weight_perturbation*PerturbationLoss(output, boxes, sigma=8, use_gpu=use_gpu)
Loss=lCount+lPerturbation# loss can become zero in some cases, where loss is a 0 valued scalar and not a tensor# So Perform gradient descent only for non zero casesiftorch.is_tensor(Loss):
Loss.backward()
optimizer.step()
pbar.set_description('Adaptation step: {:<3}, loss: {}, predicted-count: {:6.1f}'.format(step, Loss.item(), output.sum().item()))
features.required_grad=Falseoutput=adapted_regressor(features)