cv2 计算轮廓内像素点均值


代码如下:

import numpy as np
import cv2

def cal_mean_of_mask(img, contours):
    """
    输入一张图像,获取mask区域内的均值
    img : [H, W, C]
    contours : 轮廓点
    return : [每个轮廓的均值]
    """
    ret = []
    for i in range(len(contours)):
        zero_mask = np.zeros(img.shape[:2], dtype=np.uint8)
        cv2.drawContours(zero_mask, contours, i, 255, -1)
        coords = np.nonzero(zero_mask)
        ret.append(np.mean(data_array[coords]))
    return ret

思路:

定义值为 0 的, shape 同 原 img 的 mask, 在mask上绘制值为255的实心区域(轮廓内), 这样就得到了轮廓所表示的 mask 区域, 再利用 np.nonzero 函数获取所有非0点索引, 便可直接使用numpy索引data_array[coords]得到 mask 区域内的像素值, 最后使用 np.mean 计算均值即可

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以按照以下步骤实现: 1. 对轮廓进行填充,生成一个二值图像。 2. 对二值图像进行腐蚀操作,使轮廓内像素点“膨胀”一定程度,避免对比度过低的像素点被误判。 3. 对原始图像进行灰度化。 4. 遍历轮廓内的像素点计算其像素值与轮廓周围像素值的对比度,判断是否大于阈值。 5. 根据判断结果进行相应的处理。 以下是C++代码示例: ``` #include <opencv2/opencv.hpp> #include <iostream> using namespace cv; using namespace std; int main() { Mat image = imread("test.jpg"); // 读入原始图像 Mat gray; // 灰度图像 cvtColor(image, gray, COLOR_BGR2GRAY); // 转换为灰度图像 // 提取轮廓 vector<vector<Point>> contours; findContours(gray, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE); // 遍历每个轮廓 for (int i = 0; i < contours.size(); i++) { // 对轮廓进行填充,生成一个二值图像 Mat mask = Mat::zeros(gray.size(), CV_8UC1); drawContours(mask, contours, i, Scalar(255), FILLED); // 对二值图像进行腐蚀操作 Mat kernel = getStructuringElement(MORPH_ELLIPSE, Size(5, 5)); erode(mask, mask, kernel); // 遍历轮廓内的像素点 for (int j = 0; j < contours[i].size(); j++) { Point pt = contours[i][j]; // 计算像素点的对比度 double contrast = 0; for (int k = -1; k <= 1; k++) { for (int l = -1; l <= 1; l++) { int x = pt.x + k; int y = pt.y + l; if (x >= 0 && x < gray.cols && y >= 0 && y < gray.rows && mask.at<uchar>(y, x) == 255) { double diff = abs(gray.at<uchar>(pt) - gray.at<uchar>(y, x)); contrast += diff; } } } contrast /= 9; // 判断对比度是否大于阈值 double threshold = 20; // 阈值 if (contrast > threshold) { // 对比度大于阈值,进行相应的处理 // ... } } } return 0; } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值