OpenCV及rembg去除图像背景

news2024/9/25 15:27:36

OpenCV去除图像背景

去除图像背景,需要综合使用二值化(thresholding)、腐蚀(erosion)、膨胀(dilation)以及位运算(bitwise operations),代码如下:

#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>

using namespace cv;

int main(int argc, char** argv)
{
    CommandLineParser parser(argc, argv, "{@input | dog.jpg | input image}");
    // Read an image
    Mat src = imread(samples::findFile(parser.get<String>("@input")));
    if (src.empty())
    {
        std::cout << "Could not open or find the image!\n" << std::endl;
        std::cout << "Usage: " << argv[0] << " <Input image>" << std::endl;
        return EXIT_FAILURE;
    }

    // Convert the image to grayscale
    Mat grayImg;
    cvtColor(src, grayImg, COLOR_BGR2GRAY);

    // Remove the background using a threshold
    // median filter is applied to reduce noise in the image
    // ksize is 5
    Mat grayImgBlurred;
    medianBlur(grayImg, grayImgBlurred, 5);

    // A binary threshold is applied to the grayscale image using a threshold
    Mat binaryImg;
    double thresh = threshold(grayImgBlurred, binaryImg, 150, 255, THRESH_BINARY_INV);

    // Output the thresh
    std::cout << thresh << std::endl;

    // The binary image is eroded to remove small objects and fill in small gaps using erode
    Mat erodedMask;
    erode(binaryImg, erodedMask, getStructuringElement(MORPH_RECT, Size(3, 3)), Point(-1, 1), 2);

    // The binary image is dilated to expand the remaining foreground objects # and fill in gaps using dilate
    Mat mask;
    dilate(erodedMask, mask, getStructuringElement(MORPH_RECT, Size(3, 3)), Point(-1, 1), 2);

    // The original input image is combined with the binary mask using bitwise_and
    Mat backgroundRemovedImg;
    bitwise_and(src, src, backgroundRemovedImg, mask);

    // Display the processed images
    imshow("Background Removed Image", backgroundRemovedImg);
    waitKey(0);

    return EXIT_SUCCESS;
}
###Background removal is removing the background from an image

import cv2

# Read an image
img = cv2.imread('../data/dog.jpg')
# Convert the image to grayscale
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  
# Remove the background using a threshold
# median filter is applied to reduce noise in the image
gray_img = cv2.medianBlur(gray_img, 5)

# A binary threshold is applied to the grayscale image using a threshold
ret, thresh = cv2.threshold(gray_img, 150, 255, cv2.THRESH_BINARY_INV)

# The binary image is eroded to remove small objects and fill in small gaps using erode
mask = cv2.erode(thresh, None, iterations=2)

# The binary image is dilated to expand the remaining foreground objects # and fill in gaps using dilate
mask = cv2.dilate(mask, None, iterations=2)
# The original input image is combined with the binary mask using bitwise_and
background_removed_img = cv2.bitwise_and(img, img, mask=mask)

# Display the processed images 
cv2.imshow('Background Removed Image', background_removed_img)


# Wait for a key press and then close the windows
cv2.waitKey(0)
cv2.destroyAllWindows()

原图:
原来的狗狗
处理后:
处理后的狗狗
显然,这个结果并不美丽,我们可以尝试修改参数修正,但结果总是难以令人满意。于是采用更好更省事的办法,引用rembg库,调用u2net模型,去除背景。

使用rembg库去除图像背景

rembg库地址为:https://pypi.org/project/rembg/,这是一个基于机器学习模型的库,安装命令如下:

pip install rembg

如果有CUDA,可以安装GPU版:

pip install rembg[gpu]

使用该库,去除图像背景的代码如下:

### For background removal using rembg library

from rembg import remove
import cv2

#input path for image
input_path = '../data/dog.jpg'
output_path = 'output.png'

#read the image
input = cv2.imread(input_path)
output = remove(input)
# save the image 
cv2.imwrite(output_path, output)

# Display the processed images 
img = cv2.imread('output.png')
cv2.imshow('Background Removed Image', img)

# Wait for a key press and then close the windows
cv2.waitKey(0)
cv2.destroyAllWindows()

运行效果如下:

去除背景后的狗狗
效果较之于第一种方法,更简洁,当然,安装的包也是很多的。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1981429.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【独家原创RIME-CNN-LSSVM】基于霜冰优化算法优化卷积神经网络(CNN)结合最小二乘向量机(LSSVM)的数据回归预测

【独家原创RIME-CNN-LSSVM】基于霜冰优化算法优化卷积神经网络(CNN)结合最小二乘向量机(LSSVM)的数据回归预测 目录 【独家原创RIME-CNN-LSSVM】基于霜冰优化算法优化卷积神经网络(CNN)结合最小二乘向量机(LSSVM)的数据回归预测效果一览基本介绍程序设计参考资料 效果一览 基本…

成品油综合监管云平台:系统功能全方位解析

成品油综合监管云平台&#xff0c;作为集数据收集、统计分析、监管、预警应急安全等功能于一体的信息化监管系统&#xff0c;正逐步成为政府监管部门提升管理效率、保障市场秩序的重要工具。 本文将详细解析成品油综合监管云平台的多项核心功能&#xff0c;展现其在现代成品油…

习题2.31

先上代码 (defn square [x](* x x)) (defn square-tree[tree](tree-map square tree) )(defn tree-map [op tree](cond (not (seq? tree)) (op tree)(empty? tree) nil:else (cons (tree-map op (first tree)) (tree-map op (rest tree)))) )题目实际上是想让我们将树的遍历…

【网络】|wireshark

1、wireshark 1.12的使用 参考: https://blog.csdn.net/xb_zed/article/details/116305363 重点&#xff1a; 1.1 设置混杂模式

从0开始搭建vue + flask 旅游景点数据分析系统(七):可视化前后端对接实现

这一期继续编写flask后端&#xff0c;并且完成echarts折线图、柱状图和饼图的对接。 1 新增一些依赖 pip install Flask-SQLAlchemy Flask-Marshmallow pymysql修改 init.py文件&#xff0c;下面给出完整代码&#xff1a; from flask import Flask from flask_sqlalchemy im…

Studying-代码随想录训练营day57| prim算法精讲、kruskal算法精讲

第57天&#xff0c;图论07&#xff0c;两个最小生成树算法的讲解&#x1f4aa;(ง •_•)ง&#x1f4aa;&#xff0c;编程语言&#xff1a;C 目录 题目&#xff1a;53. 寻宝&#xff08;第七期模拟笔试&#xff09; (kamacoder.com) prim算法精讲 拓展 总结&#xff1a; …

新手小白嵌入式单片机教程,ESP32

1.什么是ESP32。 ESP32是一款由乐鑫信息科技&#xff08;Espressif Systems&#xff09;推出的高度集成的低功耗系统级芯片&#xff08;SoC&#xff09;&#xff0c;它结合了双核处理器、无线通信、低功耗特性和丰富的外设&#xff0c;特别适用于各种物联网&#xff08;IoT&am…

RabbitMQ如何保证可靠性

在RabbitMQ中可以将消息传递的链路简化成如下图&#xff1a; 从上图可以发现&#xff0c;主要分为三个角色&#xff1a;Producer、Consumer、RabbitMQ Broker 正常情况下&#xff0c;Producer生产消息&#xff0c;安全的到打Broker的Exchange&#xff0c;然后根据转发规则&…

springboot新农村综合展示平台-计算机毕业设计源码41793

摘 要 新农村综合展示平台是利用微信小程序开发的一种新型农村信息展示和交流平台&#xff0c;旨在通过数字化技术手段推动乡村振兴&#xff0c;促进农村资源整合和信息共享。本论文通过对新农村发展现状和需求进行分析&#xff0c;结合微信小程序开发技术&#xff0c;设计并实…

【Tessent】【Command】set_design_level Design Level

UsageDescriptionphysical_block vs. sub_blockinstrument_block set_design_level 命令的基本内容&#xff0c;以及不同 design level 之间的区分。 Usage 该命令的用法比较简单&#xff0c;主要是区分不同的 design level。 set_design_level {chip | physical_block | sub…

C++三种继承方式-公共/保护/私有继承

public、protected和private的区别在于&#xff1a; public在子类和类外都可以随意访问。 protected在子类中可以访问&#xff0c;但是在类外无法访问。 private在子类和类外都无法访问。 注意&#xff1a;父类中的所有非静态成员属性都会被子类继承下去&#xff0c;包括私有…

项目比赛项目负责人的汇报艺术:清晰、有条理地反映问题

项目比赛项目负责人的汇报艺术&#xff1a;清晰、有条理地反映问题 前言1. 现状-问题-建议&#xff1a;三步走策略2. 成绩-问题-改进&#xff1a;展示与提升3. 事实-影响-请求&#xff1a;客观与明确结语 前言 在项目管理的世界里&#xff0c;沟通不仅仅是信息的传递&#xff0…

进程的管理与控制详解:创建、终止、阻塞等待与非阻塞等待

目录 一、进程创建 1、实例 2、fork函数详解 (1)fork函数模板 (2). fork() 函数的工作原理 (3). fork() 返回值和错误处理 3、如何理解进程创建过程 二、进程终止 1、终止是在做什么&#xff1f; 2、进程终止&#xff0c;有三种情况 3、进程如何终止&#xff1f; 三…

变电站的瞬态过电压和雷击保护

瞬态过电压是电力系统的典型现象。过电压的来源是直接或附近的雷击、开关操作、电磁脉冲和静电放电。保护变电站设备免受瞬态过电压影响的经典装置是避雷器。 变电站常见的暂态过电压来自于开关操作&#xff0c;可怕的是雷电&#xff0c;它会带来较大的扰动。 雷击引起的瞬态…

ClickHouse 进阶【建表、查询优化】

1、ClickHouse 进阶 因为上一节部署了集群模式&#xff0c;所以需要启动 Zookeeper 和 ck 集群&#xff1b; 1.1、Explain 基本语法 EXPLAIN [AST | SYNTAX | PLAN | PIPELINE] [setting value, ...] SELECT ... [FORMAT ...] AST&#xff1a;用于查看语法树SYNTAX&#…

Moretl 同步设备日志到服务器

使用咨询: 扫码添加QQ 永久免费: Gitee下载最新版本 使用说明: CSDN查看使用说明 功能: 定时(全量采集or增量采集) SCADA,MES等系统采集工控机,办公电脑文件. 优势1: 开箱即用. 解压直接运行.插件集成下载. 优势2: 批管理设备. 配置均在后台配置管理. 优势3: 无人值守 采集端…

注意!!可能这是系统分析师旧教程最后一次考试,赶紧学起来

系统分析师考试是全国计算机技术与软件专业技术资格考试的高级水平考试之一&#xff0c;它是一项专业考试&#xff0c;旨在通过对计算机系统的规划、分析和设计来培养行业内的专业技术人才。近日在国家版本数据中心&#xff0c;查到系统分析师已经有2024最新版的教程出来了&…

JAVA毕业设计156—基于Java+Springboot+vue的电子招投标管理系统(源代码+数据库+万字论文)

毕设所有选题&#xff1a; https://blog.csdn.net/2303_76227485/article/details/131104075 基于JavaSpringbootvue的电子招投标管理系统(源代码数据库万字论文)156 一、系统介绍 本项目前后端分离(可以改为ssm版本)&#xff0c;分为供应商、单位、管理员三种角色 1、供应…

PMP报考条件真的需要做项目达到3年时间吗?

很多朋友想报考项目管理资格证书的时候&#xff0c;上网一看报考资格&#xff0c;一般会是这样&#xff1a; 第一类&#xff1a;拥有学士学位或同等学历以下者&#xff0c;申请者必须具备至少7500个小时的项目管理经验&#xff0c;并且在申请之日前8年内&#xff0c;累计项目管…

AI大模型加速落地 “新蓝海”如何开拓

【编者按】 当前&#xff0c;生成式人工智能技术在多个领域展现出广泛的应用潜力&#xff0c;逐渐成为科技领域的关注焦点。 国家互联网信息办公室最新数据显示&#xff0c;截至目前&#xff0c;我国已经完成备案并上线、能为公众提供服务的生成式人工智能服务大模型已达180多…