国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

使用Dino+SAM+Stable diffusion 自動進行圖片的修改

這篇具有很好參考價值的文章主要介紹了使用Dino+SAM+Stable diffusion 自動進行圖片的修改。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

SAM 是Mata發(fā)布的“Segment Anything Model”可以準確識別和提取圖像中的對象。 它可以分割任何的圖片,但是如果需要分割特定的物體,則需要需要點、框的特定提示才能準確分割圖像。 所以本文將介紹一種稱為 Grounding Dino 的技術(shù)來自動生成 SAM 進行分割所需的框。

使用Dino+SAM+Stable diffusion 自動進行圖片的修改

除了分割以外,我們還可以通過將 SAM 與 Grounding Dino 和 Stable Diffusion 相結(jié)合,獲得高度準確圖像分割結(jié)果,并且對分割后的圖像進行細微的更改。

下面就是我們需要的所有的包:

 `%cd /content
 
 !git clone https://github.com/IDEA-Research/Grounded-Segment-Anything
 
 %cd /content/Grounded-Segment-Anything 
 !pip install -q-r requirements.txt
 %cd /content/Grounded-Segment-Anything/GroundingDINO
 !pip install -q .
 %cd /content/Grounded-Segment-Anything/segment_anything
 !pip install -q .
 %cd /content/Grounded-Segment-Anything

導入必要的包:

 importos, sys
 
 sys.path.append(os.path.join(os.getcwd(), "GroundingDINO"))
 
 importargparse
 importcopy
 
 fromIPython.displayimportdisplay
 fromPILimportImage, ImageDraw, ImageFont
 fromtorchvision.opsimportbox_convert
 
 # Grounding DINO
 importGroundingDINO.groundingdino.datasets.transformsasT
 fromGroundingDINO.groundingdino.modelsimportbuild_model
 fromGroundingDINO.groundingdino.utilimportbox_ops
 fromGroundingDINO.groundingdino.util.slconfigimportSLConfig
 fromGroundingDINO.groundingdino.util.utilsimportclean_state_dict, get_phrases_from_posmap
 fromGroundingDINO.groundingdino.util.inferenceimportannotate, load_image, predict
 
 importsupervisionassv
 
 # segment anything
 fromsegment_anythingimportbuild_sam, SamPredictor
 importcv2
 importnumpyasnp
 importmatplotlib.pyplotasplt
 
 
 # diffusers
 importPIL
 importrequests
 importtorch
 fromioimportBytesIO
 fromdiffusersimportStableDiffusionInpaintPipeline
 
 
 fromhuggingface_hubimporthf_hub_download

然后我們設置處理的設備:

 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

然后我們創(chuàng)建一個 GroundingDino 模型的實例。

 defload_model_hf(repo_id, filename, ckpt_config_filename, device='cpu'):
     cache_config_file=hf_hub_download(repo_id=repo_id, filename=ckpt_config_filename)
 
     args=SLConfig.fromfile(cache_config_file) 
     args.device=device
     model=build_model(args)
     
     cache_file=hf_hub_download(repo_id=repo_id, filename=filename)
     checkpoint=torch.load(cache_file, map_location=device)
     log=model.load_state_dict(clean_state_dict(checkpoint['model']), strict=False)
     print("Model loaded from {} \n => {}".format(cache_file, log))
     _=model.eval()
     returnmodel   
 ckpt_repo_id="ShilongLiu/GroundingDINO"
 ckpt_filenmae="groundingdino_swinb_cogcoor.pth"
 ckpt_config_filename="GroundingDINO_SwinB.cfg.py"
 
 
 groundingdino_model=load_model_hf(ckpt_repo_id, ckpt_filenmae, ckpt_config_filename, device)

下面開始創(chuàng)建SAM 模型,定義模型并創(chuàng)建一個實例。

 ! wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth
 
 sam_checkpoint ='sam_vit_h_4b8939.pth'
 
 sam_predictor = SamPredictor(build_sam(checkpoint=sam_checkpoint).to(device))

這里我們使用與訓練的 vit_h 模型,下面就是擴散模型了:

 sd_pipe=StableDiffusionInpaintPipeline.from_pretrained(
     "stabilityai/stable-diffusion-2-inpainting",
     torch_dtype=torch.float16,
 ).to(device)

然后我們開始測試:

 # Load image 
 defdownload_image(url, image_file_path):
     r=requests.get(url, timeout=4.0)
     ifr.status_code!=requests.codes.ok:
         assertFalse, 'Status code error: {}.'.format(r.status_code)
 
     withImage.open(BytesIO(r.content)) asim:
         im.save(image_file_path)
     print('Image downloaded from url: {} and saved to: {}.'.format(url, image_file_path))
 
 
 local_image_path="assets/inpaint_demo.jpg"
 image_url="https://images.rawpixel.com/image_800/cHJpdmF0ZS9sci9pbWFnZXMvd2Vic2l0ZS8yMDIyLTA1L3Vwd2s2MTc3Nzk0MS13aWtpbWVkaWEtaW1hZ2Uta293YnN1MHYuanBn.jpg"
 
 download_image(image_url, local_image_path)
 image_source, image=load_image(local_image_path)
 Image.fromarray(image_source)

使用Dino+SAM+Stable diffusion 自動進行圖片的修改

先使用Grounding Dino 進行檢測:

 # detect object using grounding DINO
 defdetect(image, text_prompt, model, box_threshold=0.3, text_threshold=0.25):
   boxes, logits, phrases=predict(
       model=model, 
       image=image, 
       caption=text_prompt,
       box_threshold=box_threshold,
       text_threshold=text_threshold
   )
 
   annotated_frame=annotate(image_source=image_source, boxes=boxes, logits=logits, phrases=phrases)
   annotated_frame=annotated_frame[...,::-1] # BGR to RGB 
   returnannotated_frame, boxes
 annotated_frame, detected_boxes=detect(image, text_prompt="bench", model=groundingdino_model)
 Image.fromarray(annotated_frame)

讓我們看看結(jié)果:

使用Dino+SAM+Stable diffusion 自動進行圖片的修改

然后使用 SAM 分割這個狐貍:

 defsegment(image, sam_model, boxes):
   sam_model.set_image(image)
   H, W, _=image.shape
   boxes_xyxy=box_ops.box_cxcywh_to_xyxy(boxes) *torch.Tensor([W, H, W, H])
 
   transformed_boxes=sam_model.transform.apply_boxes_torch(boxes_xyxy.to(device), image.shape[:2])
   masks, _, _=sam_model.predict_torch(
       point_coords=None,
       point_labels=None,
       boxes=transformed_boxes,
       multimask_output=False,
       )
   returnmasks.cpu()
 
 defdraw_mask(mask, image, random_color=True):
     ifrandom_color:
         color=np.concatenate([np.random.random(3), np.array([0.8])], axis=0)
     else:
         color=np.array([30/255, 144/255, 255/255, 0.6])
     h, w=mask.shape[-2:]
     mask_image=mask.reshape(h, w, 1) *color.reshape(1, 1, -1)
     
     annotated_frame_pil=Image.fromarray(image).convert("RGBA")
     mask_image_pil=Image.fromarray((mask_image.cpu().numpy() *255).astype(np.uint8)).convert("RGBA")
 
     returnnp.array(Image.alpha_composite(annotated_frame_pil, mask_image_pil))
 segmented_frame_masks=segment(image_source, sam_predictor, boxes=detected_boxes)
 annotated_frame_with_mask=draw_mask(segmented_frame_masks[0][0], annotated_frame)
 Image.fromarray(annotated_frame_with_mask)

這樣就可以通過上面的分割結(jié)果為的擴散模型生成掩碼:

 # create mask images 
 mask=segmented_frame_masks[0][0].cpu().numpy()
 inverted_mask= ((1-mask) *255).astype(np.uint8)
 
 
 image_source_pil=Image.fromarray(image_source)
 image_mask_pil=Image.fromarray(mask)
 inverted_image_mask_pil=Image.fromarray(inverted_mask)
 
 
 display(*[image_source_pil, image_mask_pil, inverted_image_mask_pil])

使用Dino+SAM+Stable diffusion 自動進行圖片的修改

繪時我們還需要一個背景的掩碼,這個就是上面掩碼的反操作

使用Dino+SAM+Stable diffusion 自動進行圖片的修改

 defgenerate_image(image, mask, prompt, negative_prompt, pipe, seed):
   # resize for inpainting 
   w, h=image.size
   in_image=image.resize((512, 512))
   in_mask=mask.resize((512, 512))
 
   generator=torch.Generator(device).manual_seed(seed) 
 
   result=pipe(image=in_image, mask_image=in_mask, prompt=prompt, negative_prompt=negative_prompt, generator=generator)
   result=result.images[0]
 
   returnresult.resize((w, h))

然后我們可以開始改圖,輸入一個提示:

 prompt=" a brown bulldog"
 negative_prompt="low resolution, ugly"
 seed=-1# for reproducibility 
 
 generated_image=generate_image(image=image_source_pil, mask=image_mask_pil, prompt=prompt, negative_prompt=negative_prompt, pipe=sd_pipe, seed=seed)
 generated_image

使用Dino+SAM+Stable diffusion 自動進行圖片的修改

或者用上面的背景掩碼來修改背景:

 prompt="a hill with grasses ,weak sunlight "
 negative_prompt="people, low resolution, ugly"
 seed=32# for reproducibility 
 
 generated_image=generate_image(image_source_pil, inverted_image_mask_pil, prompt, negative_prompt, sd_pipe, seed)
 generated_image

使用Dino+SAM+Stable diffusion 自動進行圖片的修改

可以看到效果還是很好的

SAM、Grounding Dino 和 Stable Diffusion 的組合為我們提供了強大的工具。這些技術(shù)為探索令人興奮的圖像處理世界提供了堅實的基礎 并為藝術(shù)家和開發(fā)者提供巨大的創(chuàng)造潛力。

如果你想在線測試,這里有完整的源代碼:

https://avoid.overfit.cn/post/e9e083807a434935910c8116c85c8375

作者:Amir Shakiba文章來源地址http://www.zghlxwxcb.cn/news/detail-437379.html

到了這里,關于使用Dino+SAM+Stable diffusion 自動進行圖片的修改的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權(quán),不承擔相關法律責任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • 〔013〕Stable Diffusion 之 圖片自動評分和不健康內(nèi)容過濾器 篇

    〔013〕Stable Diffusion 之 圖片自動評分和不健康內(nèi)容過濾器 篇

    想讓系統(tǒng)幫你的圖片作品打分評價,可以下載咖啡美學自動評價插件 插件地址: https://github.com/p1atdev/stable-diffusion-webui-cafe-aesthetic 也可以通過擴展列表中搜索 cafe 點擊安裝按鈕安裝擴展 支持確定圖片是否具有 美學 和 非美學 支持單個圖片和批量評價圖片 分類類型還可

    2024年02月12日
    瀏覽(23)
  • 【計算機視覺】最強 Zero-Shot 視覺應用:Grounding DINO + Segment Anything + Stable Diffusion

    【計算機視覺】最強 Zero-Shot 視覺應用:Grounding DINO + Segment Anything + Stable Diffusion

    用 Midjourney 花一個小時做的項目 logo 圖: 解釋一下 logo 的含義:一只坐在地上的馬賽克風格的熊。 坐在地面上是因為 ground 有地面的含義,然后分割后的圖片可以認為是一種馬賽克風格,而且馬賽克諧音 mask ,之所以用熊作為 logo 主體,是因為項目主要示例的圖片是熊。 G

    2024年02月04日
    瀏覽(27)
  • 使用stable diffusion生成圖片

    使用stable diffusion生成圖片

    requirements.txt 內(nèi)容如下 保存為stable_diffusion.py并執(zhí)行 ?

    2024年02月13日
    瀏覽(94)
  • Stable Diffusion 使用 SadTalker 生成圖片數(shù)字人

    Stable Diffusion 使用 SadTalker 生成圖片數(shù)字人

    Heygen和D-ID等照片轉(zhuǎn)視頻的工具,都需要在線付費使用。本次介紹一個SadTalker數(shù)字人。SadTalker有多種使用方式,包括完整安裝程序和stable diffusion插件模式。安裝程序操作較繁瑣,因此推薦stable diffusion插件模式。 打開SD進入擴展復制鏈接 https://github.com/OpenTalker/SadTalker.git 到安裝

    2024年02月13日
    瀏覽(94)
  • SAM&Stable-Diffusion集成進化!分割、生成一切!AI繪畫新玩法

    SAM&Stable-Diffusion集成進化!分割、生成一切!AI繪畫新玩法

    自SAM「分割一切」模型推出之后,二創(chuàng)潮就開始了,有想法有行動!飛槳AI Studio開發(fā)者 會唱歌的煉丹師 就創(chuàng)作出SAM進化版,將SAM、Stable Diffusion集成,實現(xiàn)「分割」、「生成」能力二合一,并部署為應用,支持在線使用! 創(chuàng)作者:會唱歌的煉丹師 作者主頁:https://aistudio.ba

    2024年02月16日
    瀏覽(34)
  • Python 使用 Stable Diffusion API 生成圖片示例

    Python 使用 Stable Diffusion API 生成圖片示例

    代碼: 輸出: 說明: 運行后,圖片以及 JSON 將會輸出到當前目錄下 output 中; TIP: 當然前提是你已經(jīng)部署好 Stable Diffusion API 服務; 并且安裝好跟我一樣的模型以及一些相關的 LoRA ;

    2024年02月16日
    瀏覽(95)
  • 圖片生成視頻來了:Stable Video Diffusion使用教程

    11月22日 Stability AI 發(fā)布了一個AI視頻的開源項目:Stable Video Diffusion,它可以基于一張圖片生成數(shù)秒鐘的視頻,效果比較驚艷,本文就給大家分享下如何安裝和使用。 視頻不方便分享,我這里做成了gif動圖,可以看到畫面很穩(wěn)定,基本上是沒有閃爍的。 這個程序?qū)︼@卡的要求

    2024年04月14日
    瀏覽(475)
  • AI圖片生成Stable Diffusion參數(shù)及使用方式詳細介紹

    AI圖片生成Stable Diffusion參數(shù)及使用方式詳細介紹

    ????????Stable Diffusion環(huán)境搭建與運行請參考上一篇博文《AI圖片生成Stable Diffusion環(huán)境搭建與運行》,地址為“https://blog.csdn.net/suiyingy/article/details/128896426”。運行成功后,網(wǎng)頁瀏覽器顯示頁面主要包括txt2img、img2img、Extras、PNG Info、Checkpoint Merger、Train、Settings和Extensions等八

    2024年02月08日
    瀏覽(96)
  • 多模態(tài)——使用stable-video-diffusion將圖片生成視頻

    多模態(tài)——使用stable-video-diffusion將圖片生成視頻

    近期,stabilityAI發(fā)布了一個新的項目,是將圖片作為基礎,生成一個相關的小視頻,其實也算是其之前研究內(nèi)容的擴展。早在stable-diffusion的模型開源出來的時候,除了由prompt生成圖片之外,也可以生成連續(xù)幀的短視頻。 本文主要是體驗一下stable-video-diffusion的使用,以及對其

    2024年02月05日
    瀏覽(126)
  • Stable Diffusion使用civitai的模型進行AI繪圖

    Stable Diffusion使用civitai的模型進行AI繪圖

    準備工作 1.安裝Stable Diffusion(B站秋葉大佬有完整包,開箱即用) 2.啟動之后找到圖中位置下載civitai助手 下載完成之后,點擊頁面下方“重載客戶端”。 下載模型 1.進入C站,隨便找一個點進去,復制瀏覽器的網(wǎng)址 2.找到圖中的tab,如果沒有,說明civitai沒有安裝成功 ?按照圖

    2024年02月11日
    瀏覽(25)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包