当前位置:网站首页>[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 
边栏推荐
- Typora+docsify quick start
- . Net wechat message template push
- How can attribute mapping of entity classes be without it?
- Heap acwing 839 Simulated reactor
- 移动式布局(流式布局)
- About wechat enterprise payment to change x509certificate2 read certificate information, publish to the server can not access the solution
- Mobile layout (flow layout)
- Js5day (event monitoring, function assignment to variables, callback function, environment object this, select all, invert selection cases, tab column cases)
- Obtain file copyright information
- Browser storage scheme
猜你喜欢

BOM DOM

Redis sentinel mechanism and configuration

3 a VTT terminal regulator ncp51200mntxg data

js4day(DOM开始:获取DOM元素内容,修改元素样式,修改表单元素属性,setInterval定时器,轮播图案例)

模块化 CommonJS ES Module
![JDBC prevent SQL injection problems and solutions [preparedstatement]](/img/32/f71f5a31cdf710704267ff100b85d7.png)
JDBC prevent SQL injection problems and solutions [preparedstatement]

How can attribute mapping of entity classes be without it?

Linear DP acwing 899 Edit distance

线性DP AcWing 896. 最长上升子序列 II

Interesting interview questions
随机推荐
. Net, C # basic knowledge
JS10day(api 阶段性完结,正则表达式简介,自定义属性,过滤敏感词案例,注册模块验证案例)
计数类DP AcWing 900. 整数划分
1380. Lucky numbers in the matrix [two-dimensional array, matrix]
Js5day (event monitoring, function assignment to variables, callback function, environment object this, select all, invert selection cases, tab column cases)
"As a junior college student, I found out how difficult it is to counter attack after graduation."
js3day(数组操作,js冒泡排序,函数,调试窗口,作用域及作用域链,匿名函数,对象,Math对象)
模数转换器(ADC) ADE7913ARIZ 专为三相电能计量应用而设计
Mui WebView down refresh pull-up load implementation
Floyd AcWing 854. Floyd求最短路
Interesting interview questions
堆 AcWing 838. 堆排序
Browser storage scheme
Oracle from entry to mastery (4th Edition)
IPhone 6 plus is listed in Apple's "retro products" list
Hash table acwing 840 Simulated hash table
Linear DP acwing 902 Shortest editing distance
To bypass obregistercallbacks, you need to drive the signature method
Heap acwing 838 Heap sort
js1day(輸入輸出語法,數據類型,數據類型轉換,var和let區別)