python_openCV_计算图片中的区域的黑色比例

希望对原始图片进行处理,然后计算图片上的黑色和白色的占比

上图,

原始图片

python 复制代码
import numpy as np
import cv2
import  matplotlib.pyplot as plt


def cal_black(img_file):
    #功能: 计算图片中的区域的黑色比例
    #取图片中不同的位置进行计算,然后计算器数值
    #----------------
    
    percentages={}#初始化变量    
    img=cv2.imread(img_file)#step1,加载图片#fiter_1.jpg    
    shape_size=img.shape#图片的尺寸
    dic_area=split_area(shape_size)#需要检测的位置。
    #剪切图片
    part_img_1=img[y1:y2,x1:x2]
    # 灰度处理
    img_grey=cv2.cvtColor(part_img_1,cv2.COLOR_RGB2GRAY)#COLOR_BGR2GRAY
    # 高斯过滤噪音
    ret, thresh = cv2.threshold(img_grey, 127, 255, cv2.THRESH_BINARY)  
    #img_source 为处理后的图片,二值化处理后的图片\
        
    black=0
    color_black=0
    color_white=0
    shape_size=thresh.shape
    for i in range(0,shape_size[0]):
        y,x=shape_size[0],shape_size[1]
        color=thresh[i,0]#得到他得颜色RGB数值
        if color==255:
            color_white=color_white+1#白色
        else:
            color_black=color_black+1#黑色
    percentages[key]=100*color_black/(color_white+color_white)#计算黑色占比

    return percentages

在代码中主要采用了遍历进行计算,每个点计算函数的颜色然后统计,比较简单暴力,

网络上有另外的方法,摘录如下;更改其中的代码就可以。

python 复制代码
# # 应用二值化 
ret, thresh = cv2.threshold(img_grey, 80, 255, cv2.THRESH_BINARY)  #80
# ------------计算黑色像素的数量
black_pixels = np.count_nonzero(thresh == 0)
 # 计算黑色像素的数量
black_pixels2 = np.sum(thresh == 0)
# ------------计算总的像素数量
total_pixels = thresh.shape[0] * thresh.shape[1]
# ------------计算黑色像素的占比
black_ratio = black_pixels / total_pixels

print(f"黑色像素的占比: {black_ratio:.4f}")

主要用于图像特征分析。

相关推荐
IVEN_15 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang16 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮16 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling16 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮19 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽20 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞2 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽2 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers