• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Lnton羚通使用OpenCV-Python 在直方图查找显示

武飞扬头像
LNTON羚通科技
帮助1

什么是直方图?

直方图是统计图像中像素亮度或颜色等分布的一种常用工具,几乎所有图像处理的工具都提供了这种工具,X轴表示 0~255(刻度大小与Bin设置有关系),Y轴统计个数(频率)。

学新通

【代码】

学新通

OpenCV版本

import cv2
import numpy as np

src = cv2.imread('test_hist.png')
if src is None:
    print('Could not open or find the image:', 'test_hist.png')
    exit(0)

# 分离3通道
bgr_planes = cv2.split(src)

# bin的数量
histSize = 256
histRange = (0, 256)  # the upper boundary is exclusive
accumulate = False

# 计算各通道的直方图信息
b_hist = cv2.calcHist(bgr_planes, [0], None, [
                    histSize], histRange, accumulate=accumulate)
g_hist = cv2.calcHist(bgr_planes, [1], None, [
                    histSize], histRange, accumulate=accumulate)
r_hist = cv2.calcHist(bgr_planes, [2], None, [
                    histSize], histRange, accumulate=accumulate)

# 显示直方图图像的宽高
hist_w, hist_h = 512, 400
# bin 显示实际宽度
bin_w = int(round(hist_w/histSize))
histImage = np.zeros((hist_h, hist_w, 3), dtype=np.uint8)

# 数据归一化,方便显示,最小最大归一化,最小为0,最大为显示图像的高度
cv2.normalize(b_hist, b_hist, alpha=0, beta=hist_h, norm_type=cv2.NORM_MINMAX)
cv2.normalize(g_hist, g_hist, alpha=0, beta=hist_h, norm_type=cv2.NORM_MINMAX)
cv2.normalize(r_hist, r_hist, alpha=0, beta=hist_h, norm_type=cv2.NORM_MINMAX)

# 画线的方式显示信息,每个线的颜色为统计颜色
for i in range(1, histSize):
    cv2.line(histImage, (bin_w*(i-1), hist_h - int(b_hist[i-1])),
            (bin_w * (i), hist_h - int(b_hist[i])),
            (255, 0, 0), thickness=2)
    cv2.line(histImage, (bin_w*(i-1), hist_h - int(g_hist[i-1])),
            (bin_w * (i), hist_h - int(g_hist[i])),
            (0, 255, 0), thickness=2)
    cv2.line(histImage, (bin_w*(i-1), hist_h - int(r_hist[i-1])),
            (bin_w * (i), hist_h - int(r_hist[i])),
            (0, 0, 255), thickness=2)

cv2.imshow('Source image', src)
cv2.imshow('calcHist Demo', histImage)
cv2.waitKey(0)
cv2.destroyAllWindows()

NumPy版本

学新通

import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt

# img = cv2.imread('test_hist.png', 0)
# plt.hist(img.ravel(),256,[0,256]); 
# plt.show()

img = cv2.imread('test_hist.png')
color = ('b', 'g', 'r')
for i, col in enumerate(color):
    histr = cv.calcHist([img], [i], None, [256], [0, 256])
    plt.plot(histr, color=col)
    plt.xlim([0, 256])
plt.show()

Lnton羚通专注于音视频算法、算力、云平台的高科技人工智能企业。 公司基于视频分析技术、视频智能传输技术、远程监测技术以及智能语音融合技术等, 拥有多款可支持ONVIF、RTSP、GB/T28181等多协议、多路数的音视频智能分析服务器/云平台。

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhhkkkec
系列文章
更多 icon
同类精品
更多 icon
继续加载