一种去除照片背景算法

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

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()
相关推荐
TuringAcademy3 分钟前
AAAI爆款:目标检测新范式,模块化设计封神之作
论文阅读·人工智能·目标检测·论文笔记
The Open Group3 小时前
英特尔公司Darren Pulsipher 博士:以架构之力推动政府数字化转型
大数据·人工智能·架构
Ronin-Lotus4 小时前
深度学习篇---卷积核的权重
人工智能·深度学习
.银河系.4 小时前
8.18 机器学习-决策树(1)
人工智能·决策树·机器学习
敬往事一杯酒哈4 小时前
第7节 神经网络
人工智能·深度学习·神经网络
三掌柜6664 小时前
NVIDIA 技术沙龙探秘:聚焦 Physical AI 专场前沿技术
大数据·人工智能
2502_927161284 小时前
DAY 42 Grad-CAM与Hook函数
人工智能
Hello123网站4 小时前
Flowith-节点式GPT-4 驱动的AI生产力工具
人工智能·ai工具
yzx9910135 小时前
Yolov模型的演变
人工智能·算法·yolo
若天明5 小时前
深度学习-计算机视觉-微调 Fine-tune
人工智能·python·深度学习·机器学习·计算机视觉·ai·cnn