当前位置:网站首页>[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
边栏推荐
- 移动式布局(流式布局)
- What is the relationship between NFT and metauniverse? How to view the market? The future market trend of NFT
- 获取文件版权信息
- Linear DP acwing 897 Longest common subsequence
- 通过反射执行任意类的任意方法
- Five best software architecture patterns that architects must understand
- std::vector批量导入快速去重方法
- JS6day(DOM结点的查找、增加、删除。实例化时间,时间戳,时间戳的案例,重绘和回流)
- BOM DOM
- BOM DOM
猜你喜欢
bellman-ford AcWing 853. Shortest path with side limit
面渣逆袭:MySQL六十六问,两万字+五十图详解!有点六
Tencent three sides: in the process of writing files, the process crashes, and will the file data be lost?
spfa AcWing 852. spfa判断负环
BOM DOM
Interesting interview questions
Anti shake throttle
1380. Lucky numbers in the matrix [two-dimensional array, matrix]
Counting class DP acwing 900 Integer partition
js5day(事件监听,函数赋值给变量,回调函数,环境对象this,全选反选案例,tab栏案例)
随机推荐
Typora+docsify quick start
架构师必须了解的 5 种最佳软件架构模式
Std:: vector batch import fast de duplication method
Get started REPORT | today, talk about the microservice architecture currently used by Tencent
JS8day(滚动事件(scroll家族),offset家族,client家族,轮播图案例(待做))
上手报告|今天聊聊腾讯目前在用的微服务架构
获取文件版权信息
About the loading of layer web spring layer components, the position of the layer is centered
Js5day (event monitoring, function assignment to variables, callback function, environment object this, select all, invert selection cases, tab column cases)
Direct control PTZ PTZ PTZ PTZ camera debugging (c)
深拷貝 事件總線
Efficiency comparison between ArrayList and LinkedList
Js8day (rolling event (scroll family), offset family, client family, carousel map case (to be done))
The redis development document released by Alibaba covers all redis operations
JDBC prevent SQL injection problems and solutions [preparedstatement]
Linear DP acwing 898 Number triangle
Input box assembly of the shutter package
绕过ObRegisterCallbacks需要驱动签名方法
Redis sentinel mechanism and configuration
Some sudden program ideas (modular processing)