Spaces:
Sleeping
Sleeping
Update binary_segmentation.py
Browse files12345678910112 unmodified lines141516171819202122237 unmodified lines31323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612731 unmodified lines159160161162163164165"""Binary Image Segmentation ToolA lightweight, professional implementation for foreground object segmentation.Supports multiple models:- U2NETP (fastest, 1.1M params)- BiRefNet (best accuracy, larger model)- RMBG (good balance)"""import os2 unmodified linesfrom typing import Literal, Tuple, Optionalimport numpy as npimport torchfrom PIL import Imagefrom torchvision import transformsimport cv2from u2net import U2NETP# Configure logginglogging.basicConfig(7 unmodified lineslogger.info(f"Using device: {DEVICE}")class U2NETP(torch.nn.Module):"""U2-Net Portrait (U2NETP) - Lightweight segmentation model"""def __init__(self, in_ch=3, out_ch=1):super(U2NETP, self).__init__()# Encoderself.stage1 = self._make_stage(in_ch, 16, 64)self.pool12 = torch.nn.MaxPool2d(2, stride=2, ceil_mode=True)self.stage2 = self._make_stage(64, 16, 64)self.pool23 = torch.nn.MaxPool2d(2, stride=2, ceil_mode=True)self.stage3 = self._make_stage(64, 16, 64)self.pool34 = torch.nn.MaxPool2d(2, stride=2, ceil_mode=True)self.stage4 = self._make_stage(64, 16, 64)# Bridgeself.stage5 = self._make_stage(64, 16, 64)# Decoderself.stage4d = self._make_stage(128, 16, 64)self.stage3d = self._make_stage(128, 16, 64)self.stage2d = self._make_stage(128, 16, 64)self.stage1d = self._make_stage(128, 16, 64)# Side outputsself.side1 = torch.nn.Conv2d(64, out_ch, 3, padding=1)self.side2 = torch.nn.Conv2d(64, out_ch, 3, padding=1)self.side3 = torch.nn.Conv2d(64, out_ch, 3, padding=1)self.side4 = torch.nn.Conv2d(64, out_ch, 3, padding=1)self.side5 = torch.nn.Conv2d(64, out_ch, 3, padding=1)# Output fusionself.outconv = torch.nn.Conv2d(5 * out_ch, out_ch, 1)def _make_stage(self, in_ch, mid_ch, out_ch):return torch.nn.Sequential(torch.nn.Conv2d(in_ch, mid_ch, 3, padding=1),torch.nn.ReLU(inplace=True),torch.nn.Conv2d(mid_ch, mid_ch, 3, padding=1),torch.nn.ReLU(inplace=True),torch.nn.Conv2d(mid_ch, out_ch, 3, padding=1),torch.nn.ReLU(inplace=True))def forward(self, x):hx = x# Encoderhx1 = self.stage1(hx)hx = self.pool12(hx1)hx2 = self.stage2(hx)hx = self.pool23(hx2)hx3 = self.stage3(hx)hx = self.pool34(hx3)hx4 = self.stage4(hx)hx5 = self.stage5(hx4)# Decoderhx4d = self.stage4d(torch.cat((hx5, hx4), 1))hx4dup = torch.nn.functional.interpolate(hx4d, scale_factor=2, mode='bilinear', align_corners=True)hx3d = self.stage3d(torch.cat((hx4dup, hx3), 1))hx3dup = torch.nn.functional.interpolate(hx3d, scale_factor=2, mode='bilinear', align_corners=True)hx2d = self.stage2d(torch.cat((hx3dup, hx2), 1))hx2dup = torch.nn.functional.interpolate(hx2d, scale_factor=2, mode='bilinear', align_corners=True)hx1d = self.stage1d(torch.cat((hx2dup, hx1), 1))# Side outputsd1 = self.side1(hx1d)d2 = torch.nn.functional.interpolate(self.side2(hx2d), size=d1.shape[2:], mode='bilinear', align_corners=True)d3 = torch.nn.functional.interpolate(self.side3(hx3d), size=d1.shape[2:], mode='bilinear', align_corners=True)d4 = torch.nn.functional.interpolate(self.side4(hx4d), size=d1.shape[2:], mode='bilinear', align_corners=True)d5 = torch.nn.functional.interpolate(self.side5(hx5), size=d1.shape[2:], mode='bilinear', align_corners=True)# Fusiond0 = self.outconv(torch.cat((d1, d2, d3, d4, d5), 1))return torch.sigmoid(d0), torch.sigmoid(d1), torch.sigmoid(d2), torch.sigmoid(d3), torch.sigmoid(d4), torch.sigmoid(d5)class BinarySegmenter:"""Professional binary segmentation tool with multiple model backends.Args:model_type: Choice of segmentation model31 unmodified lineslogger.info(f"{self.model_type} loaded successfully")def _load_u2netp(self):"""Load U2NETP model (1.1M parameters, fastest)"""self.model = U2NETP(3, 1)# Try to load pretrained weights1234562 unmodified lines9101112131415161718197 unmodified lines2728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443531 unmodified lines467468469470471472473"""Binary Image Segmentation ToolUses the ORIGINAL U2NETP architecture to match pretrained weights perfectly."""import os2 unmodified linesfrom typing import Literal, Tuple, Optionalimport numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom PIL import Imagefrom torchvision import transformsimport cv2# Configure logginglogging.basicConfig(7 unmodified lineslogger.info(f"Using device: {DEVICE}")# ==================== ORIGINAL U2NETP ARCHITECTURE ====================# This matches your pretrained weights EXACTLY!class REBNCONV(nn.Module):def __init__(self, in_ch=3, out_ch=3, dirate=1):super(REBNCONV, self).__init__()self.conv_s1 = nn.Conv2d(in_ch, out_ch, 3, padding=1*dirate, dilation=1*dirate)self.bn_s1 = nn.BatchNorm2d(out_ch)self.relu_s1 = nn.ReLU(inplace=True)def forward(self, x):hx = xxout = self.relu_s1(self.bn_s1(self.conv_s1(hx)))return xoutdef _upsample_like(src, tar):src = F.interpolate(src, size=tar.shape[2:], mode='bilinear', align_corners=False)return srcclass RSU7(nn.Module):def __init__(self, in_ch=3, mid_ch=12, out_ch=3):super(RSU7, self).__init__()self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1)self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1)self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True)self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1)self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True)self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1)self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True)self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1)self.pool4 = nn.MaxPool2d(2, stride=2, ceil_mode=True)self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=1)self.pool5 = nn.MaxPool2d(2, stride=2, ceil_mode=True)self.rebnconv6 = REBNCONV(mid_ch, mid_ch, dirate=1)self.rebnconv7 = REBNCONV(mid_ch, mid_ch, dirate=2)self.rebnconv6d = REBNCONV(mid_ch*2, mid_ch, dirate=1)self.rebnconv5d = REBNCONV(mid_ch*2, mid_ch, dirate=1)self.rebnconv4d = REBNCONV(mid_ch*2, mid_ch, dirate=1)self.rebnconv3d = REBNCONV(mid_ch*2, mid_ch, dirate=1)self.rebnconv2d = REBNCONV(mid_ch*2, mid_ch, dirate=1)self.rebnconv1d = REBNCONV(mid_ch*2, out_ch, dirate=1)def forward(self, x):hx = xhxin = self.rebnconvin(hx)hx1 = self.rebnconv1(hxin)hx = self.pool1(hx1)hx2 = self.rebnconv2(hx)hx = self.pool2(hx2)hx3 = self.rebnconv3(hx)hx = self.pool3(hx3)hx4 = self.rebnconv4(hx)hx = self.pool4(hx4)hx5 = self.rebnconv5(hx)hx = self.pool5(hx5)hx6 = self.rebnconv6(hx)hx7 = self.rebnconv7(hx6)hx6d = self.rebnconv6d(torch.cat((hx7, hx6), 1))hx6dup = _upsample_like(hx6d, hx5)hx5d = self.rebnconv5d(torch.cat((hx6dup, hx5), 1))hx5dup = _upsample_like(hx5d, hx4)hx4d = self.rebnconv4d(torch.cat((hx5dup, hx4), 1))hx4dup = _upsample_like(hx4d, hx3)hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1))hx3dup = _upsample_like(hx3d, hx2)hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1))hx2dup = _upsample_like(hx2d, hx1)hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1))return hx1d + hxinclass RSU6(nn.Module):def __init__(self, in_ch=3, mid_ch=12, out_ch=3):super(RSU6, self).__init__()self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1)self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1)self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True)self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1)self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True)self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1)self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True)self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1)self.pool4 = nn.MaxPool2d(2, stride=2, ceil_mode=True)self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=1)self.rebnconv6 = REBNCONV(mid_ch, mid_ch, dirate=2)self.rebnconv5d = REBNCONV(mid_ch*2, mid_ch, dirate=1)self.rebnconv4d = REBNCONV(mid_ch*2, mid_ch, dirate=1)self.rebnconv3d = REBNCONV(mid_ch*2, mid_ch, dirate=1)self.rebnconv2d = REBNCONV(mid_ch*2, mid_ch, dirate=1)self.rebnconv1d = REBNCONV(mid_ch*2, out_ch, dirate=1)def forward(self, x):hx = xhxin = self.rebnconvin(hx)hx1 = self.rebnconv1(hxin)hx = self.pool1(hx1)hx2 = self.rebnconv2(hx)hx = self.pool2(hx2)hx3 = self.rebnconv3(hx)hx = self.pool3(hx3)hx4 = self.rebnconv4(hx)hx = self.pool4(hx4)hx5 = self.rebnconv5(hx)hx6 = self.rebnconv6(hx5)hx5d = self.rebnconv5d(torch.cat((hx6, hx5), 1))hx5dup = _upsample_like(hx5d, hx4)hx4d = self.rebnconv4d(torch.cat((hx5dup, hx4), 1))hx4dup = _upsample_like(hx4d, hx3)hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1))hx3dup = _upsample_like(hx3d, hx2)hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1))hx2dup = _upsample_like(hx2d, hx1)hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1))return hx1d + hxinclass RSU5(nn.Module):def __init__(self, in_ch=3, mid_ch=12, out_ch=3):super(RSU5, self).__init__()self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1)self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1)self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True)self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1)self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True)self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1)self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True)self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1)self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=2)self.rebnconv4d = REBNCONV(mid_ch*2, mid_ch, dirate=1)self.rebnconv3d = REBNCONV(mid_ch*2, mid_ch, dirate=1)self.rebnconv2d = REBNCONV(mid_ch*2, mid_ch, dirate=1)self.rebnconv1d = REBNCONV(mid_ch*2, out_ch, dirate=1)def forward(self, x):hx = xhxin = self.rebnconvin(hx)hx1 = self.rebnconv1(hxin)hx = self.pool1(hx1)hx2 = self.rebnconv2(hx)hx = self.pool2(hx2)hx3 = self.rebnconv3(hx)hx = self.pool3(hx3)hx4 = self.rebnconv4(hx)hx5 = self.rebnconv5(hx4)hx4d = self.rebnconv4d(torch.cat((hx5, hx4), 1))hx4dup = _upsample_like(hx4d, hx3)hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1))hx3dup = _upsample_like(hx3d, hx2)hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1))hx2dup = _upsample_like(hx2d, hx1)hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1))return hx1d + hxinclass RSU4(nn.Module):def __init__(self, in_ch=3, mid_ch=12, out_ch=3):super(RSU4, self).__init__()self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1)self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1)self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True)self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1)self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True)self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1)self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=2)self.rebnconv3d = REBNCONV(mid_ch*2, mid_ch, dirate=1)self.rebnconv2d = REBNCONV(mid_ch*2, mid_ch, dirate=1)self.rebnconv1d = REBNCONV(mid_ch*2, out_ch, dirate=1)def forward(self, x):hx = xhxin = self.rebnconvin(hx)hx1 = self.rebnconv1(hxin)hx = self.pool1(hx1)hx2 = self.rebnconv2(hx)hx = self.pool2(hx2)hx3 = self.rebnconv3(hx)hx4 = self.rebnconv4(hx3)hx3d = self.rebnconv3d(torch.cat((hx4, hx3), 1))hx3dup = _upsample_like(hx3d, hx2)hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1))hx2dup = _upsample_like(hx2d, hx1)hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1))return hx1d + hxinclass RSU4F(nn.Module):def __init__(self, in_ch=3, mid_ch=12, out_ch=3):super(RSU4F, self).__init__()self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1)self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1)self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=2)self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=4)self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=8)self.rebnconv3d = REBNCONV(mid_ch*2, mid_ch, dirate=4)self.rebnconv2d = REBNCONV(mid_ch*2, mid_ch, dirate=2)self.rebnconv1d = REBNCONV(mid_ch*2, out_ch, dirate=1)def forward(self, x):hx = xhxin = self.rebnconvin(hx)hx1 = self.rebnconv1(hxin)hx2 = self.rebnconv2(hx1)hx3 = self.rebnconv3(hx2)hx4 = self.rebnconv4(hx3)hx3d = self.rebnconv3d(torch.cat((hx4, hx3), 1))hx2d = self.rebnconv2d(torch.cat((hx3d, hx2), 1))hx1d = self.rebnconv1d(torch.cat((hx2d, hx1), 1))return hx1d + hxinclass U2NETP(nn.Module):"""Original U2NETP architecture - matches pretrained weights"""def __init__(self, in_ch=3, out_ch=1):super(U2NETP, self).__init__()self.stage1 = RSU7(in_ch, 16, 64)self.pool12 = nn.MaxPool2d(2, stride=2, ceil_mode=True)self.stage2 = RSU6(64, 16, 64)self.pool23 = nn.MaxPool2d(2, stride=2, ceil_mode=True)self.stage3 = RSU5(64, 16, 64)self.pool34 = nn.MaxPool2d(2, stride=2, ceil_mode=True)self.stage4 = RSU4(64, 16, 64)self.pool45 = nn.MaxPool2d(2, stride=2, ceil_mode=True)self.stage5 = RSU4F(64, 16, 64)self.pool56 = nn.MaxPool2d(2, stride=2, ceil_mode=True)self.stage6 = RSU4F(64, 16, 64)# decoderself.stage5d = RSU4F(128, 16, 64)self.stage4d = RSU4(128, 16, 64)self.stage3d = RSU5(128, 16, 64)self.stage2d = RSU6(128, 16, 64)self.stage1d = RSU7(128, 16, 64)self.side1 = nn.Conv2d(64, out_ch, 3, padding=1)self.side2 = nn.Conv2d(64, out_ch, 3, padding=1)self.side3 = nn.Conv2d(64, out_ch, 3, padding=1)self.side4 = nn.Conv2d(64, out_ch, 3, padding=1)self.side5 = nn.Conv2d(64, out_ch, 3, padding=1)self.side6 = nn.Conv2d(64, out_ch, 3, padding=1)self.outconv = nn.Conv2d(6*out_ch, out_ch, 1)def forward(self, x):hx = x# stage 1hx1 = self.stage1(hx)hx = self.pool12(hx1)# stage 2hx2 = self.stage2(hx)hx = self.pool23(hx2)# stage 3hx3 = self.stage3(hx)hx = self.pool34(hx3)# stage 4hx4 = self.stage4(hx)hx = self.pool45(hx4)# stage 5hx5 = self.stage5(hx)hx = self.pool56(hx5)# stage 6hx6 = self.stage6(hx)hx6up = _upsample_like(hx6, hx5)# decoderhx5d = self.stage5d(torch.cat((hx6up, hx5), 1))hx5dup = _upsample_like(hx5d, hx4)hx4d = self.stage4d(torch.cat((hx5dup, hx4), 1))hx4dup = _upsample_like(hx4d, hx3)hx3d = self.stage3d(torch.cat((hx4dup, hx3), 1))hx3dup = _upsample_like(hx3d, hx2)hx2d = self.stage2d(torch.cat((hx3dup, hx2), 1))hx2dup = _upsample_like(hx2d, hx1)hx1d = self.stage1d(torch.cat((hx2dup, hx1), 1))# side outputd1 = self.side1(hx1d)d2 = self.side2(hx2d)d2 = _upsample_like(d2, d1)d3 = self.side3(hx3d)d3 = _upsample_like(d3, d1)d4 = self.side4(hx4d)d4 = _upsample_like(d4, d1)d5 = self.side5(hx5d)d5 = _upsample_like(d5, d1)d6 = self.side6(hx6)d6 = _upsample_like(d6, d1)d0 = self.outconv(torch.cat((d1, d2, d3, d4, d5, d6), 1))return F.sigmoid(d0), F.sigmoid(d1), F.sigmoid(d2), F.sigmoid(d3), F.sigmoid(d4), F.sigmoid(d5), F.sigmoid(d6)# ==================== SEGMENTER CLASS ====================class BinarySegmenter:"""Professional binary segmentation tool using U2NETP.Args:model_type: Choice of segmentation model31 unmodified lineslogger.info(f"{self.model_type} loaded successfully")def _load_u2netp(self):"""Load U2NETP model with original architecture"""self.model = U2NETP(3, 1)# Try to load pretrained weights
binary_segmentation.py+387-79