当前位置:网站首页>Opencv_ 100 questions_ Chapter III (11-15)

Opencv_ 100 questions_ Chapter III (11-15)

2022-06-10 22:43:00 Fioman_ Hammer

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 Filter Is 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-MIN The 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)

原网站

版权声明
本文为[Fioman_ Hammer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206102128143559.html