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

主要用于图像特征分析。

相关推荐
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者1 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh1 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅1 天前
Python函数入门详解(定义+调用+参数)
python
曲幽1 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时1 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿1 天前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780512 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi2 天前
Chapter 2 - Python中的变量和简单的数据类型
python