当前位置:网站首页>[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 
边栏推荐
- Modular commonjs es module
- Interview with meituan, a 34 year old programmer, was rejected: only those under the age of 30 who work hard and earn little overtime
- Docsify deploy IIS
- C modifier
- 移动式布局(流式布局)
- Rust language document Lite (Part 1) - cargo, output, basic syntax, data type, ownership, structure, enumeration and pattern matching
- 线性DP AcWing 898. 数字三角形
- spfa AcWing 852. SPFA judgement negative ring
- Mobile layout (flow layout)
- bellman-ford AcWing 853. 有边数限制的最短路
猜你喜欢

js2day(又是i++和++i,if语句,三元运算符,switch、while语句,for循环语句)

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

JSON序列化 与 解析

js 迭代器 生成器 异步代码处理 promise+生成器 -> await/async
![1380. Lucky numbers in the matrix [two-dimensional array, matrix]](/img/8c/c050af5672268bc7e0df3250f7ff1d.jpg)
1380. Lucky numbers in the matrix [two-dimensional array, matrix]

spfa AcWing 851. SPFA finding the shortest path

阿里初面被两道编程题给干掉,再次内推终上岸(已拿电子offer)

模块化 CommonJS ES Module

"As a junior college student, I found out how difficult it is to counter attack after graduation."

Dijkstra AcWing 850. Dijkstra finding the shortest circuit II
随机推荐
三面阿里,有惊无险成功拿到offer定级P7,只能说是真的难
传感器 ADXL335BCPZ-RL7 3轴 加速度计 符合 RoHS/WEEE
Input box assembly of the shutter package
Dijkstra AcWing 850. Dijkstra求最短路 II
腾讯三面:进程写文件过程中,进程崩溃了,文件数据会丢吗?
基于STM32的OLED 屏幕驱动
上手报告|今天聊聊腾讯目前在用的微服务架构
Hash table acwing 841 String hash
Redis bloom filter
Mongodb redis differences
[ybtoj advanced training guidance] judgment overflow [error]
Shutter encapsulated button
通过反射执行任意类的任意方法
C modifier
Counter attack of flour dregs: MySQL 66 questions, 20000 words + 50 pictures in detail! A little six
LTC3307AHV 符合EMI标准,降压转换器 QCA7005-AL33 PHY
bellman-ford AcWing 853. Shortest path with side limit
计数类DP AcWing 900. 整数划分
. Net wechat message template push
js5day(事件监听,函数赋值给变量,回调函数,环境对象this,全选反选案例,tab栏案例)