You need to enable JavaScript to run this app. 霍夫圆(HoughCircles)检测区域直方图计算值为0问题排查
优惠活动
大模型
产品
解决方案
定价
更多

霍夫圆(HoughCircles)检测区域直方图计算值为0问题排查

问题排查与修复方案

核心错误点

  • 掩模绘制参数错误:
    1. 掩模为单通道uint8类型,需要统计的区域需赋值为255(白色),原代码传入三通道颜色值(0,255,0),单通道下仅取第一个值0,绘制的区域为黑色,无有效统计区域;
    2. 绘制圆的最后一个参数为线宽,原代码传6仅会绘制宽度为6的圆环,要统计整个圆内部区域需传-1代表填充整个圆形。
  • 存在无效循环:for indexx, ch in enumerate(pills)是无意义的遍历逻辑,重复执行掩模创建与直方图计算,没有实际作用。

修复后代码

import cv2
import numpy as np

# 读取与预处理图像
pills = cv2.imread('pill6.jpg')
gray_img = cv2.cvtColor(pills, cv2.COLOR_BGR2GRAY)
img = cv2.medianBlur(gray_img, 5)

# 霍夫圆检测
circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 70, param1=100, param2=30, minRadius=40, maxRadius=60)
if circles is not None:
    circles = np.uint16(np.around(circles))
    for i in circles[0, :]:
        # 绘制检测到的外圆
        cv2.circle(pills, (i[0], i[1]), i[2], (0, 255, 0), 6)
        
        # 创建有效掩模:填充整个圆形区域为白色255
        mask = np.zeros(img.shape[:2], dtype="uint8")
        cv2.circle(mask, (i[0], i[1]), i[2], 255, -1)
        
        # 计算灰度图在掩模区域内的直方图,也可替换为pills的指定通道
        hist_item = cv2.calcHist([gray_img], [0], mask, [256], [0, 256])
        print(f"当前圆区域直方图最大值:{max(hist_item)}")
        
        # 可取消注释查看掩模效果
        # masked_img = cv2.bitwise_and(gray_img, gray_img, mask=mask)
        # cv2.imshow("Masked Area", masked_img)
        # cv2.waitKey(0)

# 展示检测结果
cv2.imshow("Hough Circles", pills)
cv2.waitKey()
cv2.destroyAllWindows()

效果说明

修复后掩模会正确标记每个检测到的圆形内部区域,基于该掩模计算的直方图会返回有效数值,调用掩模对应的bitwise_and结果也会正常显示圆形区域内的原图内容。

内容的提问来源于stack exchange,提问作者Iyadh Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 23:06:04