4. 图片
学习函数:cv2.imread(), cv2.imshow(), cv2.imwrite()
4.1 读入图像
import numpy as np
import cv2
%matplotlib inline
print(np.__version__)
print(cv2.__version__)
img = cv2.imread("messi5.jpg", 0) # 以灰度模式读入图片
输出:
1.17.4
4.2.0
注意:如果图像的路径是错的,OpenCV也不会有任何报错或提示,但是当你使用命令print img时得到的结果是None。
4.2 显示图像
cv2.imshow("image",img) # 第一个参数:窗口的名字
cv2.waitKey(0)
cv2.destroyAllWindows()
输出:
4.3 保存图像
cv2.imwrite("messi_gray.png",img)
输出:
True
4.4 总结
img = cv2.imread("messi5.jpg",0)
cv2.imshow("image",img)
k = cv2.waitKey(0)
if k == 27:
cv2.destroyAllWindows()
elif k == ord("s"): # python ord()函数返回字符的ASCII码
cv2.imwrite("messi_gray.png",img)
cv2.destroyAllWindows()
按esc键后退出显示,不保存图片。按s健后保存成灰度图片,并退出。
from matplotlib import pyplot as plt
%matplotlib inline
plt.imshow(img, cmap="gray",interpolation="bicubic")
plt.xticks([])
plt.yticks([])
plt.show()
输出:
也可以使用matplotlib显示图片。
5. 视频
学习函数:cv2.VideoCapture(), cv2.VideoWrite()
import numpy as np
import cv2
print(np.__version__, cv2.__version__, sep="\n")
cap = cv2.VideoCapture(0)
while (True):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow("frame",gray)
if cv2.waitKey(1) == ord("q"):
break
cap.release()
cv2.destroyAllWindows()
6. OpenCV中的绘图函数
学习函数:cv2.line(), cv2.circle(), cv2.rectangle(), cv2.ellipse(), cv2.putText()
img = np.zeros((512,512,3),np.int8)
cv2.line(img,(0,0),(511,511),(255,0,0),5) # 直线:起点、终点、颜色、粗细
cv2.rectangle(img, (384,0),(510,128),(0,255,0),3) # 矩形:左上顶点、右下顶点,颜色、粗细
cv2.circle(img,(447,63),63,(0,0,255),-1) # 圆:圆心、半径、颜色
cv2.ellipse(img,(256,256),(100,50),0,0,180,155,-1) # 椭圆:中心点坐标、长短轴长度等
pts = np.array([[10,5],[20,30],[70,20],[50,10]],np.int32)
pts = pts.reshape((-1,1,2))
cv2.polylines(img,[pts],True,(0,255,255)) # 第三个参数为False时多边形不闭合
font = cv2.FONT_HERSHEY_SIMPLEX
# 添加文字:内容、位置、字体、大小、颜色、字体粗细
cv2.putText(img,"OpenCV",(10,500),font,4,(255,255,255),5)
winname = "example"
cv2.namedWindow(winname)
cv2.imshow(winname,img)
cv2.waitKey(0)
cv2.destroyAllWindows(winname)
输出:
7. 鼠标当画笔
学习函数:cv2.setMouseCallback()
7.1 简单演示
events = [i for i in dir(cv2) if "EVENT" in i]
print(events)
输出:
['EVENT_FLAG_ALTKEY', 'EVENT_FLAG_CTRLKEY', 'EVENT_FLAG_LBUTTON', 'EVENT_FLAG_MBUTTON', 'EVENT_FLAG_RBUTTON', 'EVENT_FLAG_SHIFTKEY', 'EVENT_LBUTTONDBLCLK', 'EVENT_LBUTTONDOWN', 'EVENT_LBUTTONUP', 'EVENT_MBUTTONDBLCLK', 'EVENT_MBUTTONDOWN', 'EVENT_MBUTTONUP', 'EVENT_MOUSEHWHEEL', 'EVENT_MOUSEMOVE', 'EVENT_MOUSEWHEEL', 'EVENT_RBUTTONDBLCLK', 'EVENT_RBUTTONDOWN', 'EVENT_RBUTTONUP']
def draw_circle(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDBLCLK:
cv2.circle(img, (x,y),20,(0,255,0),-1)
img = np.zeros((512,512,3),np.uint8)
cv2.namedWindow("image")
cv2.setMouseCallback("image",draw_circle)
while(1):
cv2.imshow("image",img)
if cv2.waitKey(20) == 27:
break
cv2.destroyAllWindows()
输出:
可以在显示的图像上进行“画圆圈”。
7.2 高级示例
import cv2
import numpy as np
drawing = False
mode = True
ix, iy = -1, -1
def draw_circle(event,x,y,flags,param):
global ix, iy, drawing, mode
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
ix, iy = x,y
elif event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON:
if drawing == True:
if mode == True:
cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
else:
cv2.circle(img,(x,y),3,(0,0,255),-1)
elif event == cv2.EVENT_LBUTTONUP:
drawing == False
img = np.zeros((512,512,3),np.uint8)
cv2.namedWindow("image")
cv2.setMouseCallback("image",draw_circle)
while(1):
cv2.imshow("image",img)
k = cv2.waitKey(1)
if k == ord("m"):
mode = not mode
elif k == 27:
break
输出:
可以在显示的图像上进行“画矩形”,按m键后,切换成“画圆圈”。
8. 用滑动条做调色板
学习函数:cv2.getTrackbarPos(), cv2.creatTrackbar()
import cv2
import numpy as np
def nothing(x):
pass
img = np.zeros((300,512,3),np.uint8)
cv2.namedWindow("image")
cv2.createTrackbar("R","image",0,255,nothing)
cv2.createTrackbar("G","image",0,255,nothing)
cv2.createTrackbar("B","image",0,255,nothing)
switch = "0:OFF\n1:ON"
cv2.createTrackbar(switch,"image",0,1,nothing)
while(1):
cv2.imshow("image",img)
k = cv2.waitKey(1)&0xFF
if k==27:
break
r = cv2.getTrackbarPos("R","image")
g = cv2.getTrackbarPos("G","image")
b = cv2.getTrackbarPos("B","image")
s = cv2.getTrackbarPos(switch,"image")
if s == 0:
img[:] = 0
else:
img[:]=[b,g,r]
cv2.destroyAllWindows()
输出:
调节RGB滑动条,下面矩形的颜色会发生相应的变化。