龙空技术网

2种方法用python调用cv2模块给图片打马赛克

易三一世 147

前言:

而今看官们对“python的cv2库如何安装”都比较关切,兄弟们都想要分析一些“python的cv2库如何安装”的相关资讯。那么小编在网上汇集了一些关于“python的cv2库如何安装””的相关知识,希望看官们能喜欢,兄弟们一起来了解一下吧!

1 说明:

=====

1.1 因各种需要,给图片打马赛克,当然本人着重介绍python用cv2的方法,主要讲解python和cv2的相关编程知识。

1.2 cv2模块:是OpenCV的python调用模块,本人有初步介绍,此处省略,可以看下面文章的链接:

1.3 使用图片来源,下图,来源今日头条图库。

2 方法一,指定区域打马赛克:

======================

2.1 如何选定需要打马赛克的区域,即获取左上顶点的坐标x和y,还有马赛克宽和高:

2.2 先采用基本法zhao.py显示图片,代码:

#导入模块import cv2   #读取图像,指定路径和文件夹img = cv2.imread("/home/xgj/Desktop/OpenCV/kiss.jpeg")   #窗口标题名和挂在读取图片img显示cv2.imshow("Show Your Image", img)   #不支持中文标题名#默认为0,空值就是0,如果是非0,则就是动画,一张图没效果#cv2.waitKey (0)  cv2.waitKey () cv2.destroyAllWindows()

2.3 用上面显示图片法,找坐标,如下图:

2.4 记下需要马赛克区域的x和y坐标:

即左上顶点x和y是500,300

右下角x和y是600,450

所以得到:

#左上顶点坐标500,300(x,y),右下坐标600,450(x,y)#所以需要马赛克宽100,高150do_mosaic(im, 500, 300, 100, 150)   #指定马赛克区域

2.5 mosaic1.py完整代码:

#导出模块import cv2#自定义函数def do_mosaic(frame, x, y, w, h, neighbor=9):    """    :param frame: opencv frame    :param int x :  马赛克左顶点    :param int y:  马赛克右顶点    :param int w:  马赛克宽    :param int h:  马赛克高    :param int neighbor:  马赛克每一块的宽    """    #获取这张图片的h和w,并赋值给fh和fw    fh, fw = frame.shape[0], frame.shape[1]    #判断如果超过返回    if (y + h > fh) or (x + w > fw):        return    for i in range(0, h - neighbor, neighbor):  # 关键点0 减去neightbour 防止溢出        for j in range(0, w - neighbor, neighbor):            rect = [j + x, i + y, neighbor, neighbor]            color = frame[i + y][j + x].tolist()  # 关键点1 tolist            left_up = (rect[0], rect[1])            right_down = (rect[0] + neighbor - 1, rect[1] + neighbor - 1)  # 关键点2 减去一个像素            cv2.rectangle(frame, left_up, right_down, color, -1)#读取本地图片,1代表原色就是彩色im = cv2.imread('/home/xgj/Desktop/OpenCV/kiss.jpeg', 1)#左上顶点坐标500,300(x,y),右下坐标600,450(x,y)#所以需要马赛克宽100,高150do_mosaic(im, 500, 300, 100, 150)   #指定马赛克区域while 1:    k = cv2.waitKey(10)    if k == 27:#这是一个退出设置,27代表按esc按键        break    cv2.imshow('mosaic', im)#保存生成的mosaic的图片cv2.imwrite('/home/xgj/Desktop/OpenCV/kissmosaic.jpeg', im)

2.6 效果图

3 方法二:鼠标选定打马赛克法:

========================

3.1 mosaic2.py代码:

#coding:utf-8import cv2import numpy as np#定义初始化point_start = {'x':0,'y':0}point_end = {'x':0,'y':0}rows = 0cols = 0point_lft=0point_rgt=0selected = False#定义马赛克效果函数def mosaic(selected_image,nsize=9):    rows,cols,_ = selected_image.shape    dist = selected_image.copy()    # 划分小方块,每个小方块填充随机颜色    for y in range(0,rows,nsize):        for x in range(0,cols,nsize):            dist[y:y+nsize,x:x+nsize] = (np.random.randint(0,255),np.random.randint(0,255),np.random.randint(0,255))    return dist#定义鼠标操作,选定操作,注意点击按住鼠标左键,往下拖def mouse_handler(event,x,y,flag,params):    global point_lft,point_rgt,selected    if event == cv2.EVENT_LBUTTONDOWN:        print('button down')        point_start['x'] = x        point_start['y'] = y    if event == cv2.EVENT_LBUTTONUP:        print('button up')        point_end['x'] = x        point_end['y'] = y        selected = True#导入原图  src = cv2.imread('/home/xgj/Desktop/OpenCV/kiss.jpeg')#获取原图大小和像素rows,cols,_ = src.shapesrc_cpy = src.copy()#显示原图cv2.namedWindow("src")#在原图上调用鼠标操作cv2.setMouseCallback("src",mouse_handler)#如果鼠标没有选定while not selected:    cv2.imshow('src',src)    key = cv2.waitKey(10)# 处理选择的矩形rect = {}if point_start['x'] < point_end['x']:    rect['x'] = point_start['x']    rect['y'] = point_start['y']    rect['width'] = np.abs(point_end['x'] - point_start['x'])    rect['height'] = np.abs(point_end['y'] - point_start['y'])    cv2.rectangle(src,(point_start['x'],point_start['y']),(point_end['x'],point_end['y']),(255,0,0),3)else:    rect['x'] = point_end['x']    rect['y'] = point_end['y']    rect['width'] = np.abs(point_end['x'] - point_start['x'])    rect['height'] = np.abs(point_end['y'] - point_start['y'])    cv2.rectangle(src,(point_end['x'],point_end['y']),(point_start['x'],point_start['y']),(255,0,0),3)cv2.imshow('src',src)print('selected rect = ',rect)# 选择图像select_image = src_cpy[rect['y']:rect['y']+rect['height'],                    rect['x']:rect['x']+rect['height']]result = mosaic(select_image)# 将处理完成的区域合并回原图像src_cpy[rect['y']:rect['y']+rect['height'],        rect['x']:rect['x']+rect['height']] = cv2.addWeighted(result,0.65,select_image,0.35,2.0)#显示马赛克效果的图片cv2.imshow('result',src_cpy)#保存已经生成马赛克效果的图片和位置cv2.imwrite('/home/xgj/Desktop/OpenCV/kissmosaic2.jpeg', src_cpy)cv2.waitKey()cv2.destroyAllWindows()

3.2 效果图

自己整理并分享出来,喜欢的就点赞、转发和收藏。

标签: #python的cv2库如何安装