当前位置:网站首页>[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 
边栏推荐
- Traverse entrylist method correctly
- ASP. Net MVC default configuration, if any, jumps to the corresponding program in the specified area
- 模数转换器(ADC) ADE7913ARIZ 专为三相电能计量应用而设计
- 百款拿来就能用的网页特效,不来看看吗?
- Linear DP acwing 902 Shortest editing distance
- std::vector批量导入快速去重方法
- Does C language srand need to reseed? Should srand be placed in the loop? Pseudo random function Rand
- spfa AcWing 852. spfa判断负环
- Mobile layout (flow layout)
- Browser storage scheme
猜你喜欢

浏览器node事件循环

Linear DP acwing 902 Shortest editing distance

染色法判定二分图 AcWing 860. 染色法判定二分图

NTMFS4C05NT1G N-CH 30V 11.9A MOS管,PDF

堆 AcWing 839. 模拟堆

spfa AcWing 851. SPFA finding the shortest path

What is the relationship between NFT and metauniverse? How to view the market? The future market trend of NFT

Heap acwing 839 Simulated reactor

The redis development document released by Alibaba covers all redis operations

Linear DP acwing 896 Longest ascending subsequence II
随机推荐
Linear DP acwing 895 Longest ascending subsequence
Redis sentinel mechanism and configuration
Heap acwing 838 Heap sort
About the loading of layer web spring layer components, the position of the layer is centered
Anti shake throttle
std::vector批量导入快速去重方法
. Net, C # basic knowledge
接口测试面试题目,你都会了吗?
Js10day (API phased completion, regular expression introduction, custom attributes, filtering sensitive word cases, registration module verification cases)
C modifier
阿里发布的Redis开发文档,涵盖了所有的redis操作
FBX import under ue4/ue5 runtime
Floyd AcWing 854. Floyd finds the shortest path
哈希表 AcWing 841. 字符串哈希
What data types does redis have and their application scenarios
bellman-ford AcWing 853. Shortest path with side limit
腾讯三面:进程写文件过程中,进程崩溃了,文件数据会丢吗?
Hash table acwing 840 Simulated hash table
绕过ObRegisterCallbacks需要驱动签名方法
Browser node event loop