一种去除照片背景算法

统计照片中颜色,取出最多颜色,和最多颜色比较,相近的去掉。

python 复制代码
import numpy as np
import cv2
from collections import OrderedDict
import math
def addItems(items,item):
    item=(item[0],item[1],item[2])
    if item in items.keys():
        items[item]+=1
    else:
        items[item]=1
    return items
def sort_value(old_dict, reverse=False):
    """对字典按 value 排序, 默认升序, 不修改原先字典"""
    # 获取按 value 排序后的元组列表
    items = sorted(old_dict.items(), key=lambda obj: obj[1], reverse=reverse)
    # 创建一个新的空字典
    new_dict = OrderedDict()
    # 遍历 items 列表
    for item in items:
        # item[0] 存的是 key 值
        new_dict[item[0]] = old_dict[item[0]]
    return new_dict
#除背景
def background():
    raw_img = cv2.imread(filename=r"images/01.jpg")
    # cv2.imshow("damaged image", img)
    # cv2.waitKey(0)
    # raw_img=img.copy() 
    # get the shape of the image
    height, width = raw_img.shape[0], raw_img.shape[1]
     
    #将所有点的颜色放入字典{颜色:数量}
    colors=OrderedDict()
    for i in range(height):
        for j in range(width):
            addItems(colors,raw_img[i, j])
    #按颜色数量排序
    colors=sort_value(colors)
    print(colors)
    #取数量最多的14个颜色
    max_keys=list(colors.keys())[-14:]
    #求最多颜色的平均值
    max_key=getAverage(max_keys)
    # for one in colors.keys():
    #     print(one,max_key,jl(one,max_key))
    #与最多颜色比较,距离<70的抹去
    for i in range(height):
        for j in range(width):
            p=(raw_img[i, j][0],raw_img[i, j][1],raw_img[i, j][2])
            if jl(p,max_key)<70:
                raw_img[i, j] = 0
            else:
            	pass
    #输出
    cv2.imwrite("out.jpg",raw_img)
#计算颜色平均值
def getAverage(l):
	r=[0,0,0]
	ct=0.0
	for one in l:
		r[0]=r[0]+one[0]
		r[1]=r[1]+one[1]
		r[2]=r[2]+one[2]
		ct+=1
	return(r[0]/ct,r[1]/ct,r[2]/ct)
#计算两个颜色之间距离
def jl(p1,p2):
    # print(p1,p2)
    t=(math.pow(float(p1[0])-float(p2[0]),2)+math.pow(float(p1[1])-float(p2[1]),2)+math.pow(float(p1[2])-float(p2[2]),2))
    return math.sqrt(t)
background()
相关推荐
回眸&啤酒鸭2 天前
【回眸】Minicart 电商购物车核心功能落地指南
人工智能
一隅论数智2 天前
给AI一张“业务概念地图“:本体如何从哲学走向企业智能
大数据·人工智能·经验分享·笔记·学习·学习方法·政务
AI的探索之旅2 天前
97 个 OpenCV 实例(三十):双目立体,从标定到点云
人工智能·opencv·计算机视觉
AlbertZein2 天前
Step-5-Preview 上手实测:3D 游戏、金融分析、网页设计一次跑完
人工智能·aigc
LaughingZhu2 天前
Product Hunt 每日热榜 | 2026-09-19
人工智能·深度学习·神经网络·搜索引擎·百度
美狐美颜SDK开放平台2 天前
开发直播APP时如何接入视频美颜SDK?开发流程与注意事项
android·人工智能·计算机视觉·音视频·直播美颜sdk
wukangjupingbb2 天前
智能网联汽车安全能力框架
人工智能
龙亘川2 天前
明月照湾区,智启新赛道:从顶流文旅IP盛会看智慧文旅升级路径
人工智能·智慧城市·开源软件·数据可视化
飞猫的边缘AI2 天前
边缘AI应用:家用AI摄像头怎么做数据训练?
人工智能·边缘计算·ai算法·边缘ai