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}")

主要用于图像特征分析。

相关推荐
明月_清风2 小时前
从“能用”到“专业”:构建生产级装饰器与三层逻辑拆解
后端·python
曲幽11 小时前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic
用户83562907805116 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon17 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly17 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程17 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly19 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风1 天前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风1 天前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi2 天前
08c. 检索算法与策略-混合检索
后端·python·算法