当前位置:网站首页>Opencv_ 100 questions_ Chapter III (11-15)
Opencv_ 100 questions_ Chapter III (11-15)
2022-06-10 22:43:00 【Fioman_ Hammer】
List of articles
11. Mean filter
Is to use the average value of pixels in the filter core grid as the final pixel result . Code implementation :
# @Time : 2022/6/10 11:52
# @Author : Fioman
# @Phone : 13149920693
# @Tips : Talk is Cheap,Show me the code! ^_^^_^
from settings import *
def mean_filter(image, kSize=3):
""" Mean filter , The average value of the pixels in the grid in the filter core is used as the final result to smooth the image :param image: :param kSize: :return: """
if len(image.shape) == 3:
H, W, C = image.shape
else:
image = np.expand_dims(image, axis=-1)
H, W, C = image.shape
print("C = {}".format(C))
# Zero Padding
pad = kSize // 2
out = np.zeros((H + pad * 2, W + pad * 2, C), dtype=np.float32)
out[pad:pad + H, pad:pad + W] = image.copy().astype(np.float32)
temp = out.copy()
for y in range(H):
for x in range(W):
for c in range(C):
out[pad + y, pad + x, c] = np.mean(temp[y:y + kSize, x:x + kSize, c])
out = out[pad:pad + H, pad:pad + W].astype(np.uint8)
return out
if __name__ == '__main__':
imagePath = os.path.join(OPENCV_100_Q_PATH, "gray_01.bmp")
imageOrginal = cv.imread(imagePath, cv.IMREAD_GRAYSCALE)
meanBlured = mean_filter(imageOrginal, 3)
cv.imshow("Orginal", imageOrginal)
cv.imshow("MeanBlured", meanBlured)
cv.waitKey(0)
12. Motion Filter( Motion filtering )
Motion FilterIs to take the draw value of the pixels in the main diagonal direction , A definition like this .

Code implementation :
# @Time : 2022/6/10 13:52
# @Author : Fioman
# @Phone : 13149920693
# @Tips : Talk is Cheap,Show me the code! ^_^^_^
from settings import *
def motion_filter(image, kSize=3):
if len(image.shape) == 3:
H, W, C = image.shape
else:
image = np.expand_dims(image, axis=-1)
H, W, C = image.shape
# Kernel Diagonal matrix
K = np.diag([1] * kSize).astype(np.float32)
K /= kSize # averaging
# zero padding
pad = kSize // 2
out = np.zeros((H + pad * 2, W + pad * 2, C), dtype=np.float32)
out[pad:pad + H, pad:pad + W] = image.copy().astype(np.float32)
temp = out.copy()
# filter
for y in range(H):
for x in range(W):
for c in range(C):
out[pad + y, pad + x, c] = np.sum(K * temp[y:y + kSize, x:x + kSize, c])
out = out[pad:pad + H, pad:pad + W].astype(np.uint8)
return out
if __name__ == '__main__':
imagePath = os.path.join(OPENCV_100_Q_PATH,"gray_01.bmp")
imageOriginal = cv.imread(imagePath,cv.IMREAD_GRAYSCALE)
motionFilter = motion_filter(imageOriginal,3)
cv.imshow("Original",imageOriginal)
cv.imshow("MotionFilter",motionFilter)
cv.waitKey(0)
13. MAX-MIN filter
MAX-MINThe filter is to use the difference between the maximum value and the minimum value of the pixels in the kernel size grid as the result of the pixel position assignment .
Usually used for edge detection . It is generally used on grayscale images .
Code implementation
# @Time : 2022/6/10 14:05
# @Author : Fioman
# @Phone : 13149920693
# @Tips : Talk is Cheap,Show me the code! ^_^^_^
from settings import *
def BGR_to_GRAY(image):
b = image[:, :, 0].copy()
g = image[:, :, 1].copy()
r = image[:, :, 2].copy()
# Gray scale
out = 0.2126 * r + 0.7152 * g + 0.0722 * b
out = out.astype(np.uint8)
return out
def max_min_filter(image, kSize=3):
if len(image.shape) >= 3:
image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
H, W = image.shape
# Zero padding
pad = kSize // 2
out = np.zeros((H + pad * 2, W + pad * 2), dtype=np.float32)
out[pad:pad + H, pad:pad + W] = image.copy().astype(np.float32)
temp = out.copy()
# filtering
for y in range(H):
for x in range(W):
kernelElement = temp[y:y + kSize, x:x + kSize]
out[pad + y, pad + x] = np.max(kernelElement) - np.min(kernelElement)
out = out[pad:pad + H, pad:pad + W].astype(np.uint8)
return out
if __name__ == '__main__':
imagePath = os.path.join(OPENCV_100_Q_PATH, "gray_01.bmp")
imageOriginal = cv.imread(imagePath, cv.IMREAD_GRAYSCALE)
maxMinFilter = max_min_filter(imageOriginal, 3)
cv.imshow("Original", imageOriginal)
cv.imshow("MaxMinFilter", maxMinFilter)
cv.waitKey(0)
14. Differential filter (Differential Filter)
The difference filter is actually this pixel , The difference from the previous pixel , As a result .
It is divided into horizontal and vertical , In general use 3 * 3 The matrix of .
Horizontal difference matrix , Use the difference between the calculated center point pixel and the pixel at its previous horizontal position as the result , Other positions are 0

Longitudinal difference matrix , Use the difference between the calculated center point pixel and the pixel at its previous vertical position as the result , Other positions are 0

Code implementation :
# @Time : 2022/6/10 14:26
# @Author : Fioman
# @Phone : 13149920693
# @Tips : Talk is Cheap,Show me the code! ^_^^_^
from settings import *
def BGR_to_GRAY(image):
""" :param image: :return: """
b = image[..., 0].copy()
g = image[..., 1].copy()
r = image[..., 2].copy()
out = 0.2126 * r + 0.7152 * g + 0.0722 * b
out = out.astype(np.uint8)
return out
def difference_filter(image):
if len(image.shape) == 3:
image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
H, W = image.shape
kSize = 3
# Zero Padding
pad = kSize // 2
out = np.zeros((H + pad * 2, W + pad * 2), dtype=np.float32)
out[pad:pad + H, pad:pad + W] = image.copy().astype(np.float32)
temp = out.copy()
outVer = out.copy()
outHor = out.copy()
kernelVer = np.array([[0, -1, 0], [0, 1, 0], [0, 0, 0]])
kernelHor = np.array([[0, 0, 0], [-1, 1, 0], [0, 0, 0]])
for y in range(H):
for x in range(W):
outVer[pad + y, pad + x] = np.sum(kernelVer * (temp[y:y + kSize, x:x + kSize]))
outHor[pad + y, pad + x] = np.sum(kernelHor * (temp[y:y + kSize, x:x + kSize]))
outver = np.clip(outVer, 0, 255)
outHor = np.clip(outHor, 0, 255)
outver = outver[pad:pad + H, pad:pad + W].astype(np.uint8)
outHor = outHor[pad:pad + H, pad:pad + W].astype(np.uint8)
return outver, outHor
if __name__ == '__main__':
imagePath = os.path.join(OPENCV_100_Q_PATH,"gray_01.bmp")
imageOriginal = cv.imread(imagePath,cv.IMREAD_GRAYSCALE)
difVer,difHor = difference_filter(imageOriginal)
cv.imshow("Original",imageOriginal)
cv.imshow("DifVer",difVer)
cv.imshow("DifHor",difHor)
cv.waitKey(0)
15. Sobel filter
Sobel The filter can extract a specific direction ( Vertical or horizontal ) The edge of , Filters are defined as follows : Longitudinal filter core (y The discrete derivative in the axial direction ):

Transverse filter core (x The discrete derivative in the axial direction ):

Code implementation :
# @Time : 2022/6/10 15:06
# @Author : Fioman
# @Phone : 13149920693
# @Tips : Talk is Cheap,Show me the code! ^_^^_^
from settings import *
def BGR_to_GRAY(image):
b = image[..., 0].copy()
g = image[..., 1].copy()
r = image[..., 2].copy()
out = 0.2126 * r + 0.7152 * g + 0.0722 * b
out = np.clip(out, 0, 255)
return out
def sobel_filter(image):
Ksize = 3
if len(image.shape) == 3:
image = BGR_to_GRAY(image)
H, W = image.shape
# zero padding
pad = Ksize // 2
out = np.zeros((H + pad * 2, W + pad * 2), dtype=np.float32)
out[pad:pad + H, pad:pad + W] = image.copy().astype(np.float32)
# filter
kernelX = np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]])
kernelY = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])
outX = out.copy()
outY = out.copy()
for y in range(H):
for x in range(W):
outX[y + pad, x + pad] = np.sum(kernelX * out[y:(y + Ksize), x:(x + Ksize)])
outY[y + pad, x + pad] = np.sum(kernelY * out[y:(y + Ksize), x:(x + Ksize)])
outY = np.clip(outY, 0, 255)
outX = np.clip(outX, 0, 255)
outY = outY[pad:pad + H, pad:pad + W].astype(np.uint8)
outX = outX[pad:pad + H, pad:pad + W].astype(np.uint8)
return outX, outY
if __name__ == '__main__':
imagePath = os.path.join(OPENCV_100_Q_PATH,"gray_01.bmp")
imageOriginal = cv.imread(imagePath,cv.IMREAD_GRAYSCALE)
sobelX,sobelY = sobel_filter(imageOriginal)
cv.imshow("Original",imageOriginal)
cv.imshow("SobelX",sobelX)
cv.imshow("SobelY",sobelY)
cv.waitKey(0)
边栏推荐
- How to stimulate the vitality and driving force of cultural innovation
- QT custom delegation
- Innovation and exploration are added layer by layer, and the field model of intelligent process mining tends to be mature
- [debug] could not find ref wiht POC XXX
- 进阶高级程序员必知必会. 要不然,蠢材吗
- 记录(二)
- 中小型会议如何进行数字化升级?
- Add, delete, query and modify [MySQL] table data (DML)
- 手机号码更新不出来,怎么处理
- Whale conference sharing: what should we do if the conference is difficult?
猜你喜欢
![[tcapulusdb knowledge base] tcapulusdb machine initialization and launch introduction](/img/7b/8c4f1549054ee8c0184495d9e8e378.png)
[tcapulusdb knowledge base] tcapulusdb machine initialization and launch introduction

修改SpriteMask 的 frontSortingLayer 变量
![[MySQL] Table constraints](/img/13/b97679cd4ca36d4b8e19acf23df404.png)
[MySQL] Table constraints

【小程序】Vant滑动单元格添加点击其他位置自动关闭的功能

Tcapulusdb Jun · industry news collection (V)

【TcaplusDB知识库】TcaplusDB查看进程所在机器介绍
![[tcapulusdb knowledge base] tcapulusdb tcapdb capacity expansion and contraction introduction](/img/3b/6546846fb7bbccbb0abe91422549ed.png)
[tcapulusdb knowledge base] tcapulusdb tcapdb capacity expansion and contraction introduction

TcaplusDB君 · 行业新闻汇编(三)

TcaplusDB君 · 行业新闻汇编(一)

Model construction of mmdetection
随机推荐
Diablo immortality database station address Diablo immortality database website
Management solution for whale conference smart scenic spot
TypeScript - 声明文件和内置对象
QT custom delegation
Different ways to create four indexes in MySQL
Shell basic concepts
Visio 转为高质量PDF
leetcode:333. 最大 BST 子树
Implementation of simply untyped lambda calculus
JVM运行时数据区
Mmcv Config class introduction
Reflow and repaint
存储引擎分析
【小程序】Vant-Weapp Radio单选框组件无法触发bind:Change事件
【TcaplusDB知识库】TcaplusDB TcapDB扩缩容介绍
Latex error: file ‘xxx.sty‘ not found
Visio to high quality pdf
leetcode 130. Surrounded Regions 被围绕的区域(中等)
CCF CSP 202109-2 非零段划分【100分】
Notes (V) - JVM