针对于马赛克目标检测,我们可以通过为常规图片数据集增加随机马赛克来生成数据集,当然我们也可以添加真实的马赛克图片数据。

图片增加随机马赛克的代码如下,

import os
import cv2
import random
import numpy as np

def add_random_mosaic_to_image(input_image_path, output_image_path):
    '''
    为图片添加随机马赛克
    :param input_image_path: 输入图片地址
    :param output_image_path: 输出图片地址
    :return:
    '''

    # 读取图像
    image = cv2.imread(input_image_path)
    height, width, _ = image.shape

    # 随机生产马赛克的尺寸
    mosaic_width = random.randint(0, width // 2)
    mosaic_height = random.randint(0, height // 2)

    # 随机生成马赛克的起始位置
    x = random.randint(30, width - mosaic_width)
    y = random.randint(30, height - mosaic_height)

    # 随机选择马赛克类型
    mosaic_type = random.randint(0, 1)
    if mosaic_type == 0:
        image = gaussian_mosaic(image, x, y, x + mosaic_width, y + mosaic_height)
    else:
        image = normal_mosaic(image, x, y, mosaic_width, mosaic_height)


    cv2.rectangle(image, (x, y), (x + mosaic_width, y + mosaic_height), (0, 0, 255), 2)
    cv2.imwrite(output_image_path, image)

# 高斯马赛克
def gaussian_mosaic(img, x1, y1, x2, y2):
    img[y1:y2, x1:x2, 0] = np.random.normal(size=(y2 - y1, x2 - x1))
    img[y1:y2, x1:x2, 1] = np.random.normal(size=(y2 - y1, x2 - x1))
    img[y1:y2, x1:x2, 2] = np.random.normal(size=(y2 - y1, x2 - x1))

    return img

# 正规马赛克
def normal_mosaic(img, x, y, w, h, neighbor=9):
    """
    :param rgb_img
    :param int x :  马赛克左顶点
    :param int y:  马赛克左顶点
    :param int w:  马赛克宽
    :param int h:  马赛克高
    :param int neighbor:  马赛克每一块的宽
    """
    for i in range(0, h, neighbor):
        for j in range(0, w, neighbor):
            rect = [j + x, i + y]
            color = img[i + y][j + x].tolist()  # 关键点1 tolist
            left_up = (rect[0], rect[1])
            x2 = rect[0] + neighbor - 1  # 关键点2 减去一个像素
            y2 = rect[1] + neighbor - 1
            if x2 > x + w:
                x2 = x + w
            if y2 > y + h:
                y2 = y + h
            right_down = (x2, y2)
            cv2.rectangle(img, left_up, right_down, color, -1)  # 替换为为一个颜值值

    return img

if __name__ == '__main__':
    input_image_path = './test.jpg'
    output_image_path = './test_out.jpg'

    add_random_mosaic_to_image(input_image_path, output_image_path)

上述代码为输入图片随机在任意位置贴上常规马赛克和高斯马赛克。

示例原图:

python – 为图片增加随机马赛克-StubbornHuang Blog

加上随机的正常马赛克图:

python – 为图片增加随机马赛克-StubbornHuang Blog

加上随机的高斯马赛克图:

python – 为图片增加随机马赛克-StubbornHuang Blog