一种去除照片背景算法

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

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()
相关推荐
Dev7z4 分钟前
舌苔舌象分类图像数据集
人工智能·分类·数据挖掘
新手村领路人5 分钟前
opencv gpu cuda python c++版本测试代码
python·opencv·cuda
万俟淋曦7 分钟前
【论文速递】2025年第30周(Jul-20-26)(Robotics/Embodied AI/LLM)
人工智能·深度学习·ai·机器人·论文·robotics·具身智能
TechNomad12 分钟前
十四、OpenCV中的形态学操作
opencv
高洁0119 分钟前
大模型-高效优化技术全景解析:微调 量化 剪枝 梯度裁剪与蒸馏 下
人工智能·python·深度学习·神经网络·知识图谱
CoookeCola21 分钟前
MovieNet(A holistic dataset for movie understanding) :面向电影理解的多模态综合数据集与工具链
数据仓库·人工智能·目标检测·计算机视觉·数据挖掘
张艾拉 Fun AI Everyday26 分钟前
Gartner 2025年新兴技术成熟度曲线
人工智能
菜鸟‍31 分钟前
【论文学习】大语言模型(LLM)论文
论文阅读·人工智能·学习
默 语1 小时前
AI驱动软件测试全流程自动化:从理论到实践的深度探索
运维·人工智能·驱动开发·ai·自动化·ai技术·测试全流程
说私域1 小时前
基于开源AI大模型、AI智能名片与S2B2C商城小程序的购物中心精准零售数据架构研究
人工智能·小程序·开源