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

主要用于图像特征分析。

相关推荐
时艰.几秒前
JVM — Java 类加载机制
java·开发语言·jvm
小小码农Come on20 分钟前
QT中窗口位置、相对位置、绝对位置
android·开发语言·qt
snow_star_dream20 分钟前
(笔记)VSC python应用--函数补全注释添加
笔记·python
diediedei22 分钟前
C++中的适配器模式变体
开发语言·c++·算法
郝学胜-神的一滴30 分钟前
Python中的Mixin继承:灵活组合功能的强大模式
开发语言·python·程序人生
叫我:松哥31 分钟前
基于python强化学习的自主迷宫求解,集成迷宫生成、智能体训练、模型评估等
开发语言·人工智能·python·机器学习·pygame
晚霞的不甘32 分钟前
Flutter for OpenHarmony 创意实战:打造一款炫酷的“太空舱”倒计时应用
开发语言·前端·flutter·正则表达式·前端框架·postman
2301_7644413335 分钟前
2025年YOLO算法案例应用领域应用趋势
python·yolo
WKP941836 分钟前
线程并行控制CompletableFuture
java·开发语言
飞机和胖和黄41 分钟前
考研之C语言第二周作业
c语言·开发语言·考研