如果覺得文章還行,能點(diǎn)個(gè)贊嘛?您的點(diǎn)贊是我更新的動(dòng)力??!
目錄
SAM的demo源碼使用
結(jié)合SAM,進(jìn)行人機(jī)交互ui使用的案例介紹:
最近新發(fā)現(xiàn)的,可以利用這個(gè)模型,進(jìn)行一個(gè)簡(jiǎn)單的UI使用,效果如下:
labelimg結(jié)合SAM實(shí)現(xiàn)半自動(dòng)標(biāo)注軟件
SAM的demo源碼使用
首先說(shuō)明這個(gè)鏈接里面的代碼是關(guān)于demo的,目前還不能訓(xùn)練。
原倉(cāng)庫(kù)https://github.com/facebookresearch/segment-anything
我們都知道在CV領(lǐng)域比較重要的處理圖像的幾個(gè)方向有:識(shí)別,測(cè)量(標(biāo)定),三維物體重建等。
識(shí)別是最基礎(chǔ)也是最重要的,那么分割在識(shí)別里面更是重中之重,所以這個(gè)大模型分割真的是:一個(gè)字“6”.
官方給出了demo供大家體驗(yàn)
demo
放個(gè)示例:
到上面給的鏈接(原倉(cāng)庫(kù)),去下載即可。
看到最近比較火的CV分割神器,于是思考看看代碼,在這里記錄一哈自己踩過(guò)的坑。
首先是在上面鏈接里面點(diǎn)擊code進(jìn)行下載
?然后解壓到目標(biāo)文件夾下面
然后下載模型庫(kù),放到解壓目錄文件夾下面,也就是和setup.py同一目錄下。
如果是個(gè)人筆記本的話,這里推薦vit-b
如果想要使用vit-h,建議用小分辨率的圖片并修改batch_size的大小
(即SamAutomaticMaskGenerator(sam, points_per_batch=16)),或者部署到服務(wù)器上。
配置環(huán)境,按照原文所述,環(huán)境配置為:
安裝 PyTorch 和 TorchVision 依賴項(xiàng)。強(qiáng)烈建議同時(shí)安裝具有CUDA支持的PyTorch和TorchVision.? ?python>=3.8? ?
pytorch>=1.7(如果要導(dǎo)出onnx則>=2.0)? ?
torchvision>=0.8
還有依賴庫(kù):matplotlib,pycocotools,opencv-python,onnx,onnxruntime(這些是必須安裝的)
?官方給的安裝方式有
pip install git+https://github.com/facebookresearch/segment-anything.git
或者:
git clone git@github.com:facebookresearch/segment-anything.git
cd segment-anything; pip install -e .
還有:
pip install opencv-python pycocotools matplotlib onnxruntime onnx
以上方式對(duì)于我而言好像出錯(cuò)了,我就采取的另外的方式:
利用cmd打開到解壓文件目錄里面(就是含有setup.py),然后輸入以下指令:
?進(jìn)行安裝即可,對(duì)了我是用的anconda環(huán)境,建議創(chuàng)建一個(gè)新的虛擬環(huán)境,避免干擾自己的其他配置,注意python版本一定要>=3.8
conda create -n 環(huán)境名 python=3.8
conda activate 環(huán)境名即可
python setup.py install
環(huán)境配置好以后,根據(jù)自身情況去考慮,是否采用GPU和cpu的問(wèn)題。
接下來(lái)我們開始運(yùn)行開源的demo,有兩種方式:
cmd命令:注意notebooks/images/是指你的輸入圖片路徑,output是指的輸出mask的路徑,后面的--device cpu如果加了,就會(huì)采用cpu跑,不然會(huì)默認(rèn)GPU。
python scripts/amg.py --checkpoint sam_vit_b_01ec64.pth --model-type vit_b --input notebooks/images/ --output output --device cpu
創(chuàng)建一個(gè)train.py在相同目錄下(setup.py)
里面代碼如下:
import sys
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import cv2
from segment_anything import sam_model_registry, SamAutomaticMaskGenerator, SamPredictor
matplotlib.use('TkAgg')
def show_anns(anns):
if len(anns) == 0:
return
sorted_anns = sorted(anns, key=(lambda x: x['area']), reverse=True)
ax = plt.gca()
ax.set_autoscale_on(False)
polygons = []
color = []
for ann in sorted_anns:
m = ann['segmentation']
img = np.ones((m.shape[0], m.shape[1], 3))
color_mask = np.random.random((1, 3)).tolist()[0]
for i in range(3):
img[:,:,i] = color_mask[i]
ax.imshow(np.dstack((img, m*0.35)))
sys.path.append("..")
sam_checkpoint = "sam_vit_b_01ec64.pth"
model_type = "vit_b"
device = "cuda"#如果想用cpu,改成cpu即可
sam = sam_model_registry[model_type](checkpoint=sam_checkpoint)
sam.to(device=device)
image = cv2.imread('notebooks/images/dog.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# plt.figure(figsize=(20,20))
# plt.imshow(image)
# plt.axis('off')
# plt.show()
mask_generator = SamAutomaticMaskGenerator(sam)
masks = mask_generator.generate(image)
print(len(masks))
plt.figure(figsize=(20,20))
plt.imshow(image)
show_anns(masks)
plt.axis('off')
plt.show()
# import torch # 如果pytorch安裝成功即可導(dǎo)入
# print(torch.cuda.is_available()) # 查看CUDA是否可用
# print(torch.cuda.device_count()) # 查看可用的CUDA數(shù)量
# print(torch.version.cuda) # 查看CUDA的版本號(hào)
我遇到的問(wèn)題有:
如果采用GPU運(yùn)行報(bào)錯(cuò)為:
則是因?yàn)镚PU要求內(nèi)存太大,把模型改成vit-b即可,我用vit-h就會(huì)報(bào)這個(gè)錯(cuò)了!
如果報(bào)錯(cuò)為:
?則添加以下代碼即可:
import matplotlib
matplotlib.use('TkAgg')
?最后運(yùn)行效果是這樣的:
根據(jù)相關(guān)文檔查明,如果需要導(dǎo)出onnx模型,也就是官方的下面命令:
python scripts/export_onnx_model.py --checkpoint sam_vit_b_01ec64.pth --model-type vit_b --output 輸出文件路徑
會(huì)報(bào)錯(cuò)如下:
官方更新了導(dǎo)出onnx的配置文檔,要求:
ONNX 導(dǎo)出函數(shù)使用 opset 版本 17,該版本需要 pytorch>=2.0 而不是
pytorch>=1.7
結(jié)合SAM,進(jìn)行人機(jī)交互ui使用的案例介紹:
最近新發(fā)現(xiàn)的,可以利用這個(gè)模型,進(jìn)行一個(gè)簡(jiǎn)單的UI使用,效果如下:
成功裁剪下來(lái)圖片。
首先說(shuō)明代碼不是我最開始原創(chuàng),這里只是作為分享的案例,代碼中的注釋為個(gè)人理解,如果侵權(quán),可以聯(lián)系刪除。
首先導(dǎo)入頭文件如下:
import cv2 #opencv為了讀取圖片和保存圖片
import os #因?yàn)樯婕暗阶x取文件路徑
import numpy as np #涉及到矩陣計(jì)算
from segment_anything import sam_model_registry, SamPredictor
#不用多說(shuō),為了使用SAM,因此建議,新建一個(gè)test.py,放置到與setup在同一目錄下。
按照原作者的想法是:
做一個(gè)摳圖的UI界面,底層依賴SAM,通過(guò)鼠標(biāo)點(diǎn)擊進(jìn)行人機(jī)交互。
因此首先定義了幾個(gè)函數(shù)。
nput_dir = 'input' #input文件夾名稱,用來(lái)存放即將摳圖的圖像
output_dir = 'output' #輸出圖像的文件名稱,用來(lái)?yè)笀D完畢的圖像
crop_mode=True #是否裁剪到最小范圍,在后面的判定里面會(huì)用到
#alpha_channel是否保留透明通道
print('最好是每加一個(gè)點(diǎn)就按w鍵predict一次')
os.makedirs(output_dir, exist_ok=True) #創(chuàng)建目錄
image_files = [f for f in os.listdir(input_dir) if f.lower().endswith(('.png', '.jpg', '.jpeg','.JPG','.JPEG','.PNG'))] #os.lisdir 將以圖片的格式保存的文件名,以數(shù)組的方式保存
sam = sam_model_registry["vit_b"](checkpoint="sam_vit_b_01ec64.pth")
_ = sam.to(device="cuda")#注釋掉這一行,會(huì)用cpu運(yùn)行,速度會(huì)慢很多
predictor = SamPredictor(sam)#SAM預(yù)測(cè)圖像
寫了自定義函數(shù)如下:
鼠標(biāo)點(diǎn)擊,這里運(yùn)用了opencv里面的鼠標(biāo)函數(shù)
EVENT_MOUSEMOVE 0 ? ? ? ? ? ?#滑動(dòng)
EVENT_LBUTTONDOWN 1 ? ? ? ? ?#左鍵點(diǎn)擊
EVENT_RBUTTONDOWN 2 ? ? ? ? ?#右鍵點(diǎn)擊
EVENT_MBUTTONDOWN 3 ? ? ? ? ?#中鍵點(diǎn)擊
EVENT_LBUTTONUP 4 ? ? ? ? ? ?#左鍵放開
EVENT_RBUTTONUP 5 ? ? ? ? ? ?#右鍵放開
EVENT_MBUTTONUP 6 ? ? ? ? ? ?#中鍵放開
EVENT_LBUTTONDBLCLK 7 ? ? ? ?#左鍵雙擊
EVENT_RBUTTONDBLCLK 8 ? ? ? ?#右鍵雙擊
EVENT_MBUTTONDBLCLK 9 ? ? ? ?#中鍵雙擊
def mouse_click(event, x, y, flags, param):#鼠標(biāo)點(diǎn)擊事件
global input_point, input_label, input_stop#全局變量,輸入點(diǎn),
if not input_stop:#判定標(biāo)志是否停止輸入響應(yīng)了!
if event == cv2.EVENT_LBUTTONDOWN :#鼠標(biāo)左鍵
input_point.append([x, y])
input_label.append(1)#1表示前景點(diǎn)
elif event == cv2.EVENT_RBUTTONDOWN :#鼠標(biāo)右鍵
input_point.append([x, y])
input_label.append(0)#0表示背景點(diǎn)
else:
if event == cv2.EVENT_LBUTTONDOWN or event == cv2.EVENT_RBUTTONDOWN :#提示添加不了
print('此時(shí)不能添加點(diǎn),按w退出mask選擇模式')
用來(lái)存放預(yù)測(cè)的mask
def apply_mask(image, mask, alpha_channel=True):#應(yīng)用并且響應(yīng)mask
if alpha_channel:
alpha = np.zeros_like(image[..., 0])#制作掩體
alpha[mask == 1] = 255#興趣地方標(biāo)記為1,且為白色
image = cv2.merge((image[..., 0], image[..., 1], image[..., 2], alpha))#融合圖像
else:
image = np.where(mask[..., None] == 1, image, 0)
#np.where(1,2,3) 是以1為條件,如果滿足,執(zhí)行2,否則執(zhí)行3
return image
賦予顏色到掩體上,展示到圖像
def apply_color_mask(image, mask, color, color_dark = 0.5):#對(duì)掩體進(jìn)行賦予顏色
for c in range(3):#從0->3
image[:, :, c] = np.where(mask == 1, image[:, :, c] * (1 - color_dark) + color_dark * color[c], image[:, :, c])
return image
進(jìn)行下一個(gè)圖像
def get_next_filename(base_path, filename):#進(jìn)行下一個(gè)圖像
name, ext = os.path.splitext(filename)
for i in range(1, 101):
new_name = f"{name}_{i}{ext}"
if not os.path.exists(os.path.join(base_path, new_name)):
return new_name
return None
保存ROI區(qū)域
ef save_masked_image(image, mask, output_dir, filename, crop_mode_):#保存掩蓋部分的圖像(感興趣的圖像)
if crop_mode_:
y, x = np.where(mask)
y_min, y_max, x_min, x_max = y.min(), y.max(), x.min(), x.max()
cropped_mask = mask[y_min:y_max+1, x_min:x_max+1]
cropped_image = image[y_min:y_max+1, x_min:x_max+1]
masked_image = apply_mask(cropped_image, cropped_mask)
else:
masked_image = apply_mask(image, mask)
filename = filename[:filename.rfind('.')]+'.png'
new_filename = get_next_filename(output_dir, filename)
if new_filename:
if masked_image.shape[-1] == 4:
cv2.imwrite(os.path.join(output_dir, new_filename), masked_image, [cv2.IMWRITE_PNG_COMPRESSION, 9])
else:
cv2.imwrite(os.path.join(output_dir, new_filename), masked_image)
print(f"Saved as {new_filename}")
else:
print("Could not save the image. Too many variations exist.")
定義了后面循環(huán)會(huì)用到的變量:
current_index = 0 #圖像序號(hào)
cv2.namedWindow("image") #UI窗口名稱
cv2.setMouseCallback("image", mouse_click) #鼠標(biāo)點(diǎn)擊返回作用在image window的窗口
input_point = [] #定義空數(shù)組
input_label = []
input_stop=False #定義bool
利用了三個(gè)while循環(huán)
while True:
filename = image_files[current_index]
image_orign = cv2.imread(os.path.join(input_dir, filename))
image_crop = image_orign.copy()#原圖裁剪
image = cv2.cvtColor(image_orign.copy(), cv2.COLOR_BGR2RGB)#原圖色彩轉(zhuǎn)變
selected_mask = None
logit_input= None
while True:
#print(input_point)
input_stop=False
image_display = image_orign.copy()
display_info = f'{filename} | Press s to save | Press w to predict | Press d to next image | Press a to previous image | Press space to clear | Press q to remove last point '
cv2.putText(image_display, display_info, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 255), 2, cv2.LINE_AA)
for point, label in zip(input_point, input_label):#輸入點(diǎn)和輸入類型
color = (0, 255, 0) if label == 1 else (0, 0, 255)
cv2.circle(image_display, tuple(point), 5, color, -1)
if selected_mask is not None :
color = tuple(np.random.randint(0, 256, 3).tolist())
selected_image = apply_color_mask(image_display,selected_mask, color)
cv2.imshow("image", image_display)
key = cv2.waitKey(1)
if key == ord(" "):
input_point = []
input_label = []
selected_mask = None
logit_input= None
elif key == ord("w"):
input_stop=True
if len(input_point) > 0 and len(input_label) > 0:
#todo 預(yù)測(cè)圖像
predictor.set_image(image)#設(shè)置輸入圖像
input_point_np = np.array(input_point)#輸入暗示點(diǎn),需要轉(zhuǎn)變array類型才可以輸入
input_label_np = np.array(input_label)#輸入暗示點(diǎn)的類型
#todo 輸入暗示信息,將返回masks
masks, scores, logits= predictor.predict(
point_coords=input_point_np,
point_labels=input_label_np,
mask_input=logit_input[None, :, :] if logit_input is not None else None,
multimask_output=True,
)
mask_idx=0
num_masks = len(masks)#masks的數(shù)量
while(1):
color = tuple(np.random.randint(0, 256, 3).tolist())#隨機(jī)列表顏色,就是
image_select = image_orign.copy()
selected_mask=masks[mask_idx]#選擇msks也就是,a,d切換
selected_image = apply_color_mask(image_select,selected_mask, color)
mask_info = f'Total: {num_masks} | Current: {mask_idx} | Score: {scores[mask_idx]:.2f} | Press w to confirm | Press d to next mask | Press a to previous mask | Press q to remove last point | Press s to save'
cv2.putText(selected_image, mask_info, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 255), 2, cv2.LINE_AA)
#todo 顯示在當(dāng)前的圖片,
cv2.imshow("image", selected_image)
key=cv2.waitKey(10)
if key == ord('q') and len(input_point)>0:
input_point.pop(-1)
input_label.pop(-1)
elif key == ord('s'):
save_masked_image(image_crop, selected_mask, output_dir, filename, crop_mode_=crop_mode)
elif key == ord('a') :
if mask_idx>0:
mask_idx-=1
else:
mask_idx=num_masks-1
elif key == ord('d') :
if mask_idx<num_masks-1:
mask_idx+=1
else:
mask_idx=0
elif key == ord('w') :
break
elif key == ord(" "):
input_point = []
input_label = []
selected_mask = None
logit_input= None
break
logit_input=logits[mask_idx, :, :]
print('max score:',np.argmax(scores),' select:',mask_idx)
elif key == ord('a'):
current_index = max(0, current_index - 1)
input_point = []
input_label = []
break
elif key == ord('d'):
current_index = min(len(image_files) - 1, current_index + 1)
input_point = []
input_label = []
break
elif key == 27:
break
elif key == ord('q') and len(input_point)>0:
input_point.pop(-1)
input_label.pop(-1)
elif key == ord('s') and selected_mask is not None :
save_masked_image(image_crop, selected_mask, output_dir, filename, crop_mode_=crop_mode)
if key == 27:
break
完整代碼如下:
import cv2
import os
import numpy as np
from segment_anything import sam_model_registry, SamPredictor
input_dir = 'input'
output_dir = 'output'
crop_mode=True#是否裁剪到最小范圍
#alpha_channel是否保留透明通道
print('最好是每加一個(gè)點(diǎn)就按w鍵predict一次')
os.makedirs(output_dir, exist_ok=True)
image_files = [f for f in os.listdir(input_dir) if f.lower().endswith(('.png', '.jpg', '.jpeg','.JPG','.JPEG','.PNG'))]
sam = sam_model_registry["vit_b"](checkpoint="sam_vit_b_01ec64.pth")
_ = sam.to(device="cuda")#注釋掉這一行,會(huì)用cpu運(yùn)行,速度會(huì)慢很多
predictor = SamPredictor(sam)#SAM預(yù)測(cè)圖像
def mouse_click(event, x, y, flags, param):#鼠標(biāo)點(diǎn)擊事件
global input_point, input_label, input_stop#全局變量,輸入點(diǎn),
if not input_stop:#判定標(biāo)志是否停止輸入響應(yīng)了!
if event == cv2.EVENT_LBUTTONDOWN :#鼠標(biāo)左鍵
input_point.append([x, y])
input_label.append(1)#1表示前景點(diǎn)
elif event == cv2.EVENT_RBUTTONDOWN :#鼠標(biāo)右鍵
input_point.append([x, y])
input_label.append(0)#0表示背景點(diǎn)
else:
if event == cv2.EVENT_LBUTTONDOWN or event == cv2.EVENT_RBUTTONDOWN :#提示添加不了
print('此時(shí)不能添加點(diǎn),按w退出mask選擇模式')
def apply_mask(image, mask, alpha_channel=True):#應(yīng)用并且響應(yīng)mask
if alpha_channel:
alpha = np.zeros_like(image[..., 0])#制作掩體
alpha[mask == 1] = 255#興趣地方標(biāo)記為1,且為白色
image = cv2.merge((image[..., 0], image[..., 1], image[..., 2], alpha))#融合圖像
else:
image = np.where(mask[..., None] == 1, image, 0)
return image
def apply_color_mask(image, mask, color, color_dark = 0.5):#對(duì)掩體進(jìn)行賦予顏色
for c in range(3):
image[:, :, c] = np.where(mask == 1, image[:, :, c] * (1 - color_dark) + color_dark * color[c], image[:, :, c])
return image
def get_next_filename(base_path, filename):#進(jìn)行下一個(gè)圖像
name, ext = os.path.splitext(filename)
for i in range(1, 101):
new_name = f"{name}_{i}{ext}"
if not os.path.exists(os.path.join(base_path, new_name)):
return new_name
return None
def save_masked_image(image, mask, output_dir, filename, crop_mode_):#保存掩蓋部分的圖像(感興趣的圖像)
if crop_mode_:
y, x = np.where(mask)
y_min, y_max, x_min, x_max = y.min(), y.max(), x.min(), x.max()
cropped_mask = mask[y_min:y_max+1, x_min:x_max+1]
cropped_image = image[y_min:y_max+1, x_min:x_max+1]
masked_image = apply_mask(cropped_image, cropped_mask)
else:
masked_image = apply_mask(image, mask)
filename = filename[:filename.rfind('.')]+'.png'
new_filename = get_next_filename(output_dir, filename)
if new_filename:
if masked_image.shape[-1] == 4:
cv2.imwrite(os.path.join(output_dir, new_filename), masked_image, [cv2.IMWRITE_PNG_COMPRESSION, 9])
else:
cv2.imwrite(os.path.join(output_dir, new_filename), masked_image)
print(f"Saved as {new_filename}")
else:
print("Could not save the image. Too many variations exist.")
current_index = 0
cv2.namedWindow("image")
cv2.setMouseCallback("image", mouse_click)
input_point = []
input_label = []
input_stop=False
while True:
filename = image_files[current_index]
image_orign = cv2.imread(os.path.join(input_dir, filename))
image_crop = image_orign.copy()#原圖裁剪
image = cv2.cvtColor(image_orign.copy(), cv2.COLOR_BGR2RGB)#原圖色彩轉(zhuǎn)變
selected_mask = None
logit_input= None
while True:
#print(input_point)
input_stop=False
image_display = image_orign.copy()
display_info = f'{filename} | Press s to save | Press w to predict | Press d to next image | Press a to previous image | Press space to clear | Press q to remove last point '
cv2.putText(image_display, display_info, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 255), 2, cv2.LINE_AA)
for point, label in zip(input_point, input_label):#輸入點(diǎn)和輸入類型
color = (0, 255, 0) if label == 1 else (0, 0, 255)
cv2.circle(image_display, tuple(point), 5, color, -1)
if selected_mask is not None :
color = tuple(np.random.randint(0, 256, 3).tolist())
selected_image = apply_color_mask(image_display,selected_mask, color)
cv2.imshow("image", image_display)
key = cv2.waitKey(1)
if key == ord(" "):
input_point = []
input_label = []
selected_mask = None
logit_input= None
elif key == ord("w"):
input_stop=True
if len(input_point) > 0 and len(input_label) > 0:
#todo 預(yù)測(cè)圖像
predictor.set_image(image)#設(shè)置輸入圖像
input_point_np = np.array(input_point)#輸入暗示點(diǎn),需要轉(zhuǎn)變array類型才可以輸入
input_label_np = np.array(input_label)#輸入暗示點(diǎn)的類型
#todo 輸入暗示信息,將返回masks
masks, scores, logits= predictor.predict(
point_coords=input_point_np,
point_labels=input_label_np,
mask_input=logit_input[None, :, :] if logit_input is not None else None,
multimask_output=True,
)
mask_idx=0
num_masks = len(masks)#masks的數(shù)量
while(1):
color = tuple(np.random.randint(0, 256, 3).tolist())#隨機(jī)列表顏色,就是
image_select = image_orign.copy()
selected_mask=masks[mask_idx]#選擇msks也就是,a,d切換
selected_image = apply_color_mask(image_select,selected_mask, color)
mask_info = f'Total: {num_masks} | Current: {mask_idx} | Score: {scores[mask_idx]:.2f} | Press w to confirm | Press d to next mask | Press a to previous mask | Press q to remove last point | Press s to save'
cv2.putText(selected_image, mask_info, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 255), 2, cv2.LINE_AA)
#todo 顯示在當(dāng)前的圖片,
cv2.imshow("image", selected_image)
key=cv2.waitKey(10)
if key == ord('q') and len(input_point)>0:
input_point.pop(-1)
input_label.pop(-1)
elif key == ord('s'):
save_masked_image(image_crop, selected_mask, output_dir, filename, crop_mode_=crop_mode)
elif key == ord('a') :
if mask_idx>0:
mask_idx-=1
else:
mask_idx=num_masks-1
elif key == ord('d') :
if mask_idx<num_masks-1:
mask_idx+=1
else:
mask_idx=0
elif key == ord('w') :
break
elif key == ord(" "):
input_point = []
input_label = []
selected_mask = None
logit_input= None
break
logit_input=logits[mask_idx, :, :]
print('max score:',np.argmax(scores),' select:',mask_idx)
elif key == ord('a'):
current_index = max(0, current_index - 1)
input_point = []
input_label = []
break
elif key == ord('d'):
current_index = min(len(image_files) - 1, current_index + 1)
input_point = []
input_label = []
break
elif key == 27:
break
elif key == ord('q') and len(input_point)>0:
input_point.pop(-1)
input_label.pop(-1)
elif key == ord('s') and selected_mask is not None :
save_masked_image(image_crop, selected_mask, output_dir, filename, crop_mode_=crop_mode)
if key == 27:
break
使用方法,如下:
使用gui(環(huán)境要配置好,再開始),另外注意下述的w,s,q按鍵均要在英文輸入法下使用
1.將待摳圖的圖片放到input文件夾中,然后啟動(dòng)程序(運(yùn)行test.py)。
2、在圖像上左鍵單擊選擇前景點(diǎn)(綠色),右鍵單擊選擇背景點(diǎn)(紅色)。
3、按下w鍵使用模型進(jìn)行預(yù)測(cè),進(jìn)入Mask選取模式。
4、在Mask選取模式下,可以按下a和d鍵切換不同的Mask。
5、按下s鍵保存摳圖結(jié)果。
6、按下w鍵返回選點(diǎn)模式,下次模型將會(huì)在此mask基礎(chǔ)上進(jìn)行預(yù)測(cè)
7、按 q 鍵刪除最新一個(gè)選定的點(diǎn)
利用裁剪下來(lái)的圖片進(jìn)行,融合,也就是常說(shuō)的換背景圖:
博文鏈接如下:
實(shí)現(xiàn)圖片的裁剪和融合。_Helloorld_1的博客-CSDN博客
新的研究思考:
可以結(jié)合labelimg和SAM進(jìn)行半自動(dòng)標(biāo)注軟件,雖然百度里面也有智能標(biāo)注easy,但是下載數(shù)據(jù)集很麻煩。
labelimg結(jié)合SAM實(shí)現(xiàn)半自動(dòng)標(biāo)注軟件
這里有一個(gè)案例希望可以幫助到大家,代碼的地址:
gyhdc/LabelSAM-for-yolo: 簡(jiǎn)易的yolo半自動(dòng)標(biāo)注庫(kù),目前只支持單目標(biāo)。如果數(shù)據(jù)集圖片背景復(fù)雜,可能工作量不比直接標(biāo)的小,因?yàn)閟am是通用的分割模型。但是可以適當(dāng)通過(guò)調(diào)整參數(shù)修改。 (github.com)https://github.com/gyhdc/LabelSAM-for-yolo由一位UP博主開源的倉(cāng)庫(kù),供大家學(xué)習(xí),如上述所敘述,是結(jié)合labelimg和SAM來(lái)實(shí)現(xiàn)自動(dòng)化標(biāo)注。
效果如下:
效果還行,這里是將的所有識(shí)別出來(lái)的物體,都進(jìn)行標(biāo)注了,所以看著會(huì)比較亂(因此,按照原文所述,這個(gè)工具適合單一目標(biāo)物體的輔助標(biāo)注,背景最好簡(jiǎn)單點(diǎn))。
本文只是補(bǔ)充說(shuō)明,開源代碼的使用。
下載(download zip)上述倉(cāng)庫(kù)代碼:
進(jìn)行解壓:
?如果配置了SAM環(huán)境了,這里就可以不用管了。
將前面下載的vit-b模型放到文件夾model下面即可。
將要自動(dòng)標(biāo)注的圖片放到images / train下即可
最后生成的標(biāo)注數(shù)據(jù)會(huì)被放到labels/ train里面去。
pycharm打開并運(yùn)行main.py
默認(rèn)是vit-b模型,運(yùn)行即可,會(huì)批量完成文件夾下的圖片標(biāo)注。
標(biāo)注完成后會(huì)得到這些(txt-標(biāo)注信息)文件:
?然后咱們就可以打開labelimg進(jìn)行輔助標(biāo)注了。
win+R,輸入cmd,(也可以直接在上面txt文件夾上方輸入cmd+enter回車鍵)
打開環(huán)境
conda activate 環(huán)境名(前面創(chuàng)建的)
?如果沒(méi)有l(wèi)abelimg,可以安裝:
pip install labelimg -i https://pypi.tuna.tsinghua.edu.cn/simple
?使用labelimg,只需要在cmd中輸入:
labelimg
就會(huì)出來(lái)這個(gè)界面?
按照上述標(biāo)號(hào),將路徑選擇完,就會(huì)出現(xiàn):
可以delete進(jìn)行多余標(biāo)注刪除。當(dāng)然這個(gè)案例本身作用不大,但是帶來(lái)了思考如何讓SAM為我們服務(wù),標(biāo)注本來(lái)就是一件特別繁瑣的事。?
百度結(jié)合SAM,產(chǎn)生的PaddleSeg文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-427613.html
參考鏈接如下:pasddleseg文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-427613.html
到了這里,關(guān)于Segment Anything(SAM)的demo的簡(jiǎn)單使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!