MCPcopy Create free account
hub / github.com/aigc3d/LHM / birefnet_predict_bbox

Method birefnet_predict_bbox

engine/SegmentAPI/SAM.py:227–287  ·  view source on GitHub ↗
(self, img, scale=1.0)

Source from the content-addressed store, hash-verified

225 return scale_box, pha[..., 0]
226
227 def birefnet_predict_bbox(self, img, scale=1.0):
228
229 # img: RGB-order
230
231 if self.box_prior == None:
232 from engine.BiRefNet.utils import check_state_dict
233
234 birefnet = BiRefNet(bb_pretrained=False)
235 state_dict = torch.load(BIREFNET_WEIGHT, map_location="cpu")
236 state_dict = check_state_dict(state_dict)
237 birefnet.load_state_dict(state_dict)
238 device = avaliable_device()
239 torch.set_float32_matmul_precision(["high", "highest"][0])
240
241 birefnet.to(device)
242 self.box_prior = birefnet
243 self.box_prior.eval()
244 self.box_transform = transforms.Compose(
245 [
246 transforms.Resize((1024, 1024)),
247 transforms.ToTensor(),
248 transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
249 ]
250 )
251 print("BiRefNet is ready to use.")
252 else:
253 device = avaliable_device()
254 self.box_prior.to(device)
255
256 height, width, _ = img.shape
257
258 image = PIL.Image.fromarray(img)
259
260 input_images = self.box_transform(image).unsqueeze(0).to("cuda")
261 with torch.no_grad():
262 preds = self.box_prior(input_images)[-1].sigmoid().cpu()
263 pha = (preds[0]).squeeze(0).detach().numpy()
264
265 pha = cv2.resize(pha, (width, height))
266
267 masks = copy.deepcopy(pha[..., None])
268
269 masks[masks < 0.3] = 0.0
270 masks[masks >= 0.3] = 1.0
271
272 # obtain bbox
273 _h, _w, _ = np.where(masks == 1)
274
275 whwh = [
276 _w.min().item(),
277 _h.min().item(),
278 _w.max().item(),
279 _h.max().item(),
280 ]
281
282 box = Bbox(whwh)
283
284 # scale box to 1.05

Callers 1

_forwardMethod · 0.95

Calls 12

scaleMethod · 0.95
BiRefNetClass · 0.90
check_state_dictFunction · 0.90
BboxClass · 0.90
printFunction · 0.85
evalMethod · 0.80
cpuMethod · 0.80
maxMethod · 0.80
avaliable_deviceFunction · 0.70
loadMethod · 0.45
toMethod · 0.45
resizeMethod · 0.45

Tested by

no test coverage detected