获取某种颜色在图片中所占的比例

  如何在一张图片中找到与自己想要的颜色值最相近的颜色,并且求出这些颜色在整张图片中所占的比例。比如对着一片绿地拍了一张照片然后想要查看一下那片绿地在整张照片中的范围,大概估算一下绿地的面积等等类似的场景。虽然不一定准确但是还是会有一定的参考价值。
核心算法代码:

/*
init_red, init_green, init_blue --- 需要查找到的颜色值
red, green, blue --- 图片中的颜色值
deffirence --- 容差(需要的颜色值和需要的颜色值的容差)
*/
bool magic_pixel(BYTE init_red, BYTE init_green, BYTE init_blue,  BYTE red, BYTE green, BYTE blue, int deffirence){
	if( deffirence > Max(abs(init_red - red), abs(init_green - green), abs(init_blue - blue))){
		return true;
	}else{
		return false;
	}
}

原图:
这里写图片描述

软件处理:
这里写图片描述

效果图:
这里写图片描述

  以上可以看到我是选取了云彩的颜色然后经过处理后,与乌云颜色容差较大的绿地的色彩被过滤掉了。可以看到图片上面显示了,与我选择的乌云的颜色相近的颜色值占整张的面积是69.12%。

环境:Win8.1 + VS2008 + CxImage

源码下载地址

  • 1
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
要计算图片颜色比例,可以使用Python中的Pillow库。具体步骤如下: 1. 导入Pillow库: ``` python from PIL import Image ``` 2. 打开图片获取像素数据: ``` python img = Image.open('image.jpg') pixels = img.load() ``` 3. 定义一个字典用于记录颜色出现的次数: ``` python color_count = {} ``` 4. 遍历每个像素,统计每种颜色出现的次数: ``` python for i in range(img.size[0]): for j in range(img.size[1]): color = pixels[i, j] if color in color_count: color_count[color] += 1 else: color_count[color] = 1 ``` 5. 计算每种颜色出现的比例: ``` python total_pixels = img.size[0] * img.size[1] color_ratio = {} for color, count in color_count.items(): ratio = count / total_pixels color_ratio[color] = ratio ``` 其中,`total_pixels` 表示图片的总像素数,`count` 表示某种颜色图片中出现的次数。 6. 输出每种颜色比例: ``` python for color, ratio in color_ratio.items(): print('颜色{0}的比例为{1:.2%}'.format(color, ratio)) ``` 注意,上述代码中的 `color` 是一个三元组,表示RGB颜色,例如 `(255, 255, 255)` 表示白色。`ratio` 是一个小数,需要乘以100才是百分数。`:.2%` 表示输出小数点后两位。 完整代码示例: ``` python from PIL import Image img = Image.open('image.jpg') pixels = img.load() color_count = {} for i in range(img.size[0]): for j in range(img.size[1]): color = pixels[i, j] if color in color_count: color_count[color] += 1 else: color_count[color] = 1 total_pixels = img.size[0] * img.size[1] color_ratio = {} for color, count in color_count.items(): ratio = count / total_pixels color_ratio[color] = ratio for color, ratio in color_ratio.items(): print('颜色{0}的比例为{1:.2%}'.format(color, ratio)) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wb175208

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值