当前位置:网站首页>[opencv learning] [image histogram and equalization]
[opencv learning] [image histogram and equalization]
2022-07-02 12:52:00 【A sea of stars】
Today, learn image histogram and image equalization
One : Image histogram
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Histogram of the image , It is to count which pixels , Or the number of pixels in that pixel range
# stay opencv Is used in calcHist(images, channels, mask, histSzie, ranges)
# Argument parsing :
# images: Multiple images can be transferred in at one time . The incoming image is a list, use [] Cover up , The data type is uint8/float32
# channels: Which channel is counted , If the grayscale image is imported [0], If it's a color image , Pass in [0]、[1]、[2], It stands for BGR passageway
# mask: Mask the image , If you want to count this image , Is the incoming None, If you want to count only a part , You need to make a mask to pass in
# histSzie: BIN The number of , Divide into several ranges on average , If it is a range of pixels , Namely 256.
# ranges: Range of pixels , Usually it is [0, 256]
# Show the image , Encapsulate as a function
def cv_show_image(name, img):
cv2.imshow(name, img)
cv2.waitKey(0) # Waiting time , In milliseconds ,0 Represents any key termination
cv2.destroyAllWindows()
img = cv2.imread('images/saoge2.jpg')
print(img.shape)
plt.hist(img.ravel(), 256)
plt.title('src_img_hist')
plt.show()
# Calculate the histogram of each channel
hist_b = cv2.calcHist([img], [0], None, [256], [0, 256])
print(hist_b.shape) # (256, 1)
hist_g = cv2.calcHist([img], [1], None, [256], [0, 256])
print(hist_g.shape) # (256, 1)
hist_r = cv2.calcHist([img], [2], None, [256], [0, 256])
print(hist_r.shape) # (256, 1)
# Draw this BGR Histogram of three channels
plt.plot(hist_b, 'b')
plt.plot(hist_g, 'g')
plt.plot(hist_r, 'r')
plt.xlim([0, 256])
plt.title('bgr_hist')
plt.show()
# With mask operation , When we only want to take part of the region for histogram statistics , You can use the mask
# Mask is the selected area is reserved , The unselected area is abandoned , Therefore, the value of the mask in the selection area is 255, The value of the discarded area is 0
# Here's the definition mask The way of mask
mask = np.zeros(img.shape[:2], np.uint8)
mask[100:300, 100:540] = 255
masked_img = cv2.bitwise_and(img, img, mask=mask) # Get the image after flax action
hist_full_img = cv2.calcHist([img], [0], None, [256], [0, 256])
hist_mask_img = cv2.calcHist([img], [0], mask, [256], [0, 256])
plt.subplot(2,2,1), plt.imshow(img, 'gray')
plt.subplot(2,2,2), plt.imshow(mask, 'gray')
plt.subplot(2,2,3), plt.imshow(masked_img, 'gray')
plt.subplot(2,2,4), plt.plot(hist_full_img, 'b'), plt.plot(hist_mask_img, 'g')
plt.xlim([0, 256])
plt.title('mask_hist')
plt.show()
The gray histogram of the original image is :
Of the original image BGR Histogram of three channels 
Of the original image B Masked B Channel histogram 
Two : Histogram equalization
# Histogram equalization
# After getting the histogram , Some histograms have uneven pixel distribution , The color is very biased , Therefore, it needs to be balanced and adjusted
# The purpose of image equalization is to improve the contrast of the image . For the image with concentrated gray distribution ( The whole is too dark or too bright ), Can play a balanced role ( There is light and dark ).
# The way is :
# Read image
# Count the pixel values for each channel separately [0,255] Number of occurrences .
# Calculate the pixel value of each channel separately [0,255] Probability of occurrence , Get the probability histogram .
# Calculate the pixel value of each channel separately [0,255] Cumulative sum of probabilities , Get the cumulative probability histogram .
# Calculate the pixel mapping function for each channel according to the cumulative probability histogram . Complete the mapping of each pixel for each channel .
# for instance , The pixel value is 56 The cumulative probability of is 0.2, Then the pixel value is 56 The new mapped pixel value of is 256*0.2=51
# for instance , The pixel value is 255 The cumulative probability of must be 1, The pixel value is 255 The new mapped pixel value of is 256*01=255
# Output histogram equalization image .
# stay opencv The operation
# Read the original image
img = cv2.imread('images/saoge2.jpg', cv2.IMREAD_GRAYSCALE) # Read gray image
plt.hist(img.ravel(), 256)
plt.title('src_img_hist')
plt.show()
# Image histogram equalization , The whole image will be equalized
equ = cv2.equalizeHist(img)
plt.hist(equ.ravel(), 256)
plt.title('equalizeHist_img')
plt.show()
# Adaptive equalization
# Divide the image into small squares , Do their own equalization
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
res_clahe = clahe.apply(img)
res = np.hstack((img, equ, res_clahe))
cv_show_image('equalizeHist', res)
Comparison of the effects of general equalization and adaptive equalization 
边栏推荐
- Fluent fluent library encapsulation
- Linear DP acwing 896 Longest ascending subsequence II
- spfa AcWing 852. SPFA judgement negative ring
- 软件测试面试题-2022年大厂面试题合集
- Anti shake throttle
- 正确遍历EntryList方法
- Js4day (DOM start: get DOM element content, modify element style, modify form element attributes, setinterval timer, carousel Map Case)
- js2day(又是i++和++i,if语句,三元运算符,switch、while语句,for循环语句)
- Mongodb redis differences
- Redis avalanche, penetration, breakdown
猜你喜欢

趣味 面试题

3 a VTT terminal regulator ncp51200mntxg data

LTC3307AHV 符合EMI标准,降压转换器 QCA7005-AL33 PHY

Linear DP acwing 895 Longest ascending subsequence

应用LNK306GN-TL 转换器、非隔离电源

C modifier

Day4 operator, self increasing, self decreasing, logical operator, bit operation, binary conversion decimal, ternary operator, package mechanism, document comment

Mobile layout (flow layout)

线性DP AcWing 897. 最长公共子序列
![[ybtoj advanced training guidance] cross the river [BFS]](/img/4e/83f14452ea6410768cdd01e725af2e.jpg)
[ybtoj advanced training guidance] cross the river [BFS]
随机推荐
spfa AcWing 851. SPFA finding the shortest path
绕过ObRegisterCallbacks需要驱动签名方法
[ybtoj advanced training guidance] cross the river [BFS]
Sensor adxl335bcpz-rl7 3-axis accelerometer complies with rohs/weee
线性DP AcWing 895. 最长上升子序列
Enhance network security of kubernetes with cilium
架构师必须了解的 5 种最佳软件架构模式
Deep copy event bus
JSON序列化 与 解析
难忘阿里,4面技术5面HR附加笔试面,走的真艰难真心酸
std::vector批量导入快速去重方法
. Net, C # basic knowledge
Input box assembly of the shutter package
About the loading of layer web spring layer components, the position of the layer is centered
传感器 ADXL335BCPZ-RL7 3轴 加速度计 符合 RoHS/WEEE
2.6 using recursion and stack - [tower of Hanoi problem]
Analog to digital converter (ADC) ade7913ariz is specially designed for three-phase energy metering applications
Interesting interview questions
染色法判定二分图 AcWing 860. 染色法判定二分图
js1day(輸入輸出語法,數據類型,數據類型轉換,var和let區別)