本文主要是将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()