import sys
sys.path.append("..")
sys.path.insert(0, '.')
import argparse
import torch
import torch.nn as nn
from PIL import Image
import numpy as np
import cv2
import time
import imutils
import lib.transform_cv2 as T
from lib.models import model_factory
from configs import set_cfg_from_file
torch.set_grad_enabled(False)
np.random.seed(123)
path = 'G:/3.jpg' # 原图
imgFile = Image.open(path).convert('RGB')
newImage = imgFile.resize((640, 480), Image.BILINEAR)
path = path.split(".")
path = path[0] + '.png'
newImage.save(path)
img1 = cv2.imread(path) # 原图
# args
parse = argparse.ArgumentParser()
#parse.add_argument('--config', dest='config', type=str, default='BiSeNet-master/configs/bisenetv2_city.py',)
parse.add_argument('--config', dest='config', type=str, default='./configs/bisenetv2_city.py',)#../ 退回进BiSeNet-master文件夹下
# parse.add_argument('--weight-path', type=str, default='BiSeNet-master/res/model_final_v2_city.pth',)
parse.add_argument('--weight-path', type=str, default='./waterv5_model_final.pth',)
#parse.add_argument('--weight-path', type=str, default='./res/model_final.pth',)
#parse.add_argument('--img-path', dest='img_path', type=str, default='BiSeNet-master/example.png',)
parse.add_argument('--img-path', dest='img_path', type=str, default= path,)
args = parse.parse_args()
cfg = set_cfg_from_file(args.config)
# palette = np.random.randint(0, 256, (256, 3), dtype=np.uint8)
palette = np.array([[0, 0, 0], [255, 255, 255]], dtype=np.uint8)
# define model
net = model_factory[cfg.model_type](cfg.n_cats, aux_mode='pred')
net.load_state_dict(torch.load(args.weight_path, map_location='cpu'), strict=False)
net.eval()
to_tensor = T.ToTensor(
mean=(0.3257, 0.3690, 0.3223), # city, rgb
std=(0.2112, 0.2148, 0.2115),
)
im = cv2.imread(args.img_path)[:, :, ::-1]
# im = to_tensor(dict(im=im, lb=None))['im'].unsqueeze(0).cuda()
im = to_tensor(dict(im=im, lb=None))['im'].unsqueeze(0)
# inference
t1 = time.time()
out = net(im).squeeze().detach().cpu().numpy()
t2 = time.time()
print('time cost: %.6f'%(t2-t1))
pred = palette[out]
#cv2.imwrite('BiSeNet-master/resv2.jpg', pred)
# cv2.imwrite('output.jpg', pred)
# cv2.namedWindow("output", cv2.WINDOW_NORMAL)
# cv2.imshow("output", pred)
# cv2.waitKey(0)
# img = cv2.imread('output.png') # mask黑白图
# if np.count_nonzero(pred > 0) > 153: # 5%的地方找到最大轮廓并框出来
ret,thresh = cv2.threshold(cv2.cvtColor(pred,cv2.COLOR_BGR2GRAY),127,255,0)
# contours,hierarchy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
contours,hierarchy=cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
contours.sort(key=lambda c: cv2.contourArea(c), reverse=True)
cnt=contours[0]
x,y,w,h=cv2.boundingRect(cnt)
#Straight Bounding Rectangle
cv2.rectangle(img1,(x,y),(x+w,y+h),(0,0,255),2)
cv2.imshow('boundingRect',img1)
# cv2.resizeWindow('boundingRect', 640, 480)
# cv2.imshow('boundingRect',cv2.WINDOW_NORMAL)
cv2.namedWindow("boundingRect", cv2.WINDOW_NORMAL)
cv2.waitKey(0)
cv2.destroyAllWindows()
结果:



