一种去除照片背景算法

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

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()
相关推荐
小陈phd27 分钟前
高级RAG策略学习(五)——llama_index实现上下文窗口增强检索RAG
人工智能
凯禾瑞华养老实训室2 小时前
人才教育导向下:老年生活照护实训室助力提升学生老年照护服务能力
人工智能
湫兮之风3 小时前
Opencv: cv::LUT()深入解析图像块快速查表变换
人工智能·opencv·计算机视觉
Christo34 小时前
TFS-2018《On the convergence of the sparse possibilistic c-means algorithm》
人工智能·算法·机器学习·数据挖掘
qq_508823404 小时前
金融量化指标--2Alpha 阿尔法
大数据·人工智能
黑金IT4 小时前
`.cursorrules` 与 `.cursorcontext`:Cursor AI 编程助手时代下的“双轨配置”指南
人工智能
学弟4 小时前
快捷:常见ocr学术数据集预处理版本汇总(适配mmocr)
计算机视觉
dlraba8025 小时前
基于 OpenCV 的信用卡数字识别:从原理到实现
人工智能·opencv·计算机视觉
IMER SIMPLE5 小时前
人工智能-python-深度学习-经典神经网络AlexNet
人工智能·python·深度学习
小憩-7 小时前
【机器学习】吴恩达机器学习笔记
人工智能·笔记·机器学习