OpenCV-Python 教程1: 画个背景变色小猪脸

 

本文主要是将OpenCV-Python tutorials :Gui Features 这一部分所设计的知识点,做一个综合demo。主要涉及以下问题:

1.图片的读入、保存、展示

image	=cv.imread(filename,flags) #flags: ImreadModes 读入图片的模式 
cv2.imshow('窗口名称',image) #窗口会自动适应图片大小

如果我们使用其他展示方式,例如matplotlib.pyplot 由于opencv读入的图片顺序是 BGR 所以我们需要进行调整顺序才能正常的展示。

具体问题阐述与解答

cv.imwrite(filepath,image) #将图片image保存

2. 画线、圆、长方形等

3.鼠标点击事件

4.设置各种trackbars

 

我们将上面进行综合,实现一个简单的可交互的demo,通过调节trackbars改变小猪脸的背景,并且可以自行在上面进行绘画(长方形和曲线),支持按s键保存图片。

import numpy as np
import cv2 as cv

# mouse callback function
def draw_circle(event,x,y,flags,param):
    global ix,iy,drawing,mode
    if event == cv.EVENT_LBUTTONDOWN:
        drawing = True
        ix,iy = x,y
    elif event == cv.EVENT_MOUSEMOVE:
        if drawing == True:
            if mode == True:
                cv.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
            else:
                cv.circle(img,(x,y),5,(0,0,255),-1)
    elif event == cv.EVENT_LBUTTONUP:
        drawing = False
        if mode == True:
            cv.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
        else:
            cv.circle(img,(x,y),5,(0,0,255),-1)
            
            
def nothing(x):
    pass
def drawpigface(img):
    cv.circle(img,(256,128), 63, (0,0,255), 3)
    cv.circle(img,(210,70), 15, (0,0,255), 3)
    cv.circle(img,(300,70), 15, (0,0,255), 3)
    cv.ellipse(img,(256,150),(20,10),0,0,180,255,3)
    cv.circle(img,(225,100), 5, (0,0,255), 3)
    cv.circle(img,(285,100), 5, (0,0,255), 3)

    pts = np.array([[256,128],[242,140],[270,140]], np.int32)
    pts = pts.reshape((-1,1,2))
    cv.polylines(img,[pts],True,(0,255,255),2)

    font = cv.FONT_HERSHEY_SIMPLEX
    cv.putText(img,'I am hah',(10,250), font,3,(255,255,255),2,cv.LINE_AA)
 



img = np.zeros((400,512,3), np.uint8)
drawing = False # 是否画控制变量
mode = True # 画长方形还是曲线控制变量
ix,iy = -1,-1

cv.namedWindow('image')

cv.createTrackbar('R','image',0,255,nothing)
cv.createTrackbar('G','image',0,255,nothing)
cv.createTrackbar('B','image',0,255,nothing)
switch = '0 : OFF \n1 : ON'
cv.createTrackbar(switch, 'image',0,1,nothing)

cv.setMouseCallback('image',draw_circle)

while(1):
    cv.imshow('image',img)
    k = cv.waitKey(1) & 0xFF
    if k == 27:
        break
    elif k == ord('m'):
        mode = not mode
    elif k == ord('s'):
        cv.imwrite('D:\\Users\\scalett\\Desktop\\pig.jpg',img)
        break 

    # get current positions of four trackbars
    r = cv.getTrackbarPos('R','image')
    g = cv.getTrackbarPos('G','image')
    b = cv.getTrackbarPos('B','image')
    s = cv.getTrackbarPos(switch,'image')
    if s == 0:
        img[:] = img
        drawpigface(img)

    else:
        img[:] = [b,g,r] #注意opencv是BGR
        drawpigface(img)
cv.destroyAllWindows()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值