>### 说明END >##import cv2
import numpy as np
# 将直⽅图(填充)转化为图⽚
def calcAndDrawHist(image, color):
hist = cv2.calcHist([image], [0], None, [256], [0.0,255.0])
# cv2.minMaxLoc 最⼤值maxVal和最⼩值minVal及它们的位置企业为什么要上市
minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(hist)
麦冬的功效与作用# 创建全零图像
histImg = np.zeros([256,256,3], np.uint8)
hpt = int(0.95* 256);
for h in range(256):
# hpt=0.95*256 0.95防⽌最⼤值为整张图⽚的⾼,每个hist与最⼤值的⽐*(256*0.95)即可表⽰该hist在图⽚中的⾼度
intensity = int(hist[h]*hpt/maxVal)
# cv2.line(图像img,第⼀个点坐标(x1,y1),第⼆个点坐标(x2,y2),颜⾊[b,g,r])
cv2.line(histImg,(h,256), (h,256-intensity), color)
return histImg
# 将直⽅图(折线)转化为图⽚
def DrawHist(img):
# 建⽴空图⽚
h = np.zeros((256,256,3))
# 直⽅图中各bin的顶点位置
bins = np.arange(256).reshape(256,1)
# BGR三种颜⾊
color = [ (255,0,0),(0,255,0),(0,0,255) ]
for ch, col in enumerate(color):
originHist = cv2.calcHist([img],[ch],None,[256],[0,256])
# alize(图像img,输出图像,归⼀化后最低值,归⼀化后最⼤值,规范化类型 cv2.NORM_M
INMAX:仅针对密集阵列) alize(originHist, originHist,0,255*0.9,cv2.NORM_MINMAX)
# np.around(array) 取整数,但数据类型仍为float
hist=np.int32(np.around(originHist))
hist=np.int32(np.around(originHist))
# np.column_stack 将两个1-D数组作为列堆叠成2维数组
pts = np.column_stack((bins,hist))
# cv2.polylines(图像img,多边形曲线的数组,绘制的折线是否关闭的标志,折线颜⾊) cv2.polylines(h,[pts],Fal,col)
# np.flipud 在上/下⽅向翻转数组。
h=np.flipud(h)
return h
'''
>## 灰度图像———直⽅图(填充) >##img = cv2.imread('001.jpg',0)
histimg = calcAndDrawHist(img,[255,255,255])
李翊君歌曲cv2.imshow('hist',histimg)
cv2.waitKey(0)
'''
>## 彩⾊图像———直⽅图(填充) >##if __name__ == '__main__':
# 读取图⽚
img = cv2.imread("001.jpg")
# cv2.spilt 返回BGR三个通道
b, g, r = cv2.split(img)
# calcAndDrawHist(图像img,color填[b,g,r])
histImgB = calcAndDrawHist(b, [255, 0, 0])
histImgG = calcAndDrawHist(g, [0, 255, 0])
histImgR = calcAndDrawHist(r, [0, 0, 255])
cv2.imshow("histImgB", histImgB)
cv2.imshow("histImgG", histImgG)
cv2.imshow("histImgR", histImgR)
cv2.imshow("Img", img)
>## 彩⾊图像———直⽅图(折线) >##if __name__ == '__main__':
img = cv2.imread("001.jpg")
h = DrawHist(img)
cv2.imshow('colorhist',h)
cv2.waitKey(0)
cv2.destroyAllWindows()
结果显⽰:
彩⾊图像———直⽅图(填充)
彩⾊图像———直⽅图(折线)
5.形态学运算:膨胀与腐蚀
# -*- coding: utf-8 -*-
# @Author: Xingmo
import cv2
import numpy as np
小便时尿出血是怎么回事# 读取图像
img = cv2.imread('004.jpg',0);
# 构造⼀个3×3的结构元素
element = StructuringElement(cv2.MORPH_RECT,(3, 3))
# 膨胀图像 cv2.dilate(图像,元素结构)
dilate = cv2.dilate(img, element)
# 腐蚀图像 de(图像,元素结构)
erode = de(img, element)
# 将两幅图像相减获得边,第⼀个参数是膨胀后的图像,第⼆个参数是腐蚀后的图像
result = cv2.absdiff(dilate,erode);
# 上⾯得到的结果是灰度图,cv2.threshold将其⼆值化以便更清楚的观察结果
# cv2.threshold(src , thresh, maxval, type[, dst]) 返回retval、dst
# cv2.threshold(图像, 阈值 , 最⼤值, 阈值类型) 返回值类型、返回处理后图像
# 阈值类型:THRESH_BINARY、THRESH_BINARY_INV、THRESH_TRUNC、THRESH_TOZERO、THRESH_TOZERO_INV retval, result = cv2.threshold(result, 40, 255, cv2.THRESH_BINARY);
# 反⾊,即对⼆值图每个像素取反
result = cv2.bitwi_not(result);
# 显⽰图像
cv2.imshow("origin",img); # 原图
cv2.imshow("result",result);# 边缘检测图
cv2.waitKey(0)
cv2.destroyAllWindows()
结果显⽰: