8 bits(位值)-> 256 levels(分辨率)
灰度图像:0黑色-255白色,将灰色分成256级,一层
全彩图像RGB:颜色通道(红、绿、蓝),三层,每层的0-255代表该层颜色的亮度
像素:
VGA:640*480
HD:1280*720
FHD:1920*1080
4K:3840*2160
打开照片:
import numpy as np
import matplotlib.pyplot
import cv2 as cv
img = cv.imread("Picture\love.jpg")
#要在项目工作空间的文件夹里的照片才行
"""img = cv2.imread("Picture\love.jpg",cv2.IMREAD_GRAYSCALE)"""
#后面的第二参数是转化成灰度图
# C:\Users\zhaohaobing\PycharmProjects\python-opencv-project\picture
cv.imshow("love",img)
#照片名字不能用中文的
cv.waitKey(0)
#等待时间,毫米级,0代表任意键才终止
cv.destroyAllWindows()
#任意键关闭
cv.imwrite('picture\ mylove.png',img)
#将照片保存
print(img.shape)
#(1200, 1920, 3) h w c(3层还是1层)
print(type(img))
#格式
print(img.size)
#像素点个数
print(img.dtype)
#uint8 数据类型 8位
读取视频:
import numpy as np
import matplotlib.pyplot
import cv2 as cv
vc = cv.VideoCapture("video\How do you use your time.mp4")
if vc.isOpened():
open,frame = vc.read()
#open返回一个True或False,vc.read()是取第一帧第二帧...赋给frame
else:
open = False
while open:
ret,frame = vc.read()
if frame is None:
break
if ret == True:
#gray = cv.cvtColor(frame,cv.COLOR_BGRA2GRAY)
#灰度处理
cv.imshow("mytime",frame)
if cv.waitKey(10) == ord("q"):
#按q键退出键推出视频
break
vc.release()
cv.destroyAllWindows()
打开摄像头:
import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
#一般电脑内置摄像头为0,可以通过设置成 1 或者其他的来选择别的摄像头
if not cap.isOpened():
print("Cannot open camera")
while True:
# Capture frame-by-frame
ret, frame = cap.read()
# if frame is read correctly ret is True
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
# Our operations on the frame come here
#gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)#你也可以注释掉这行颜色转换的代码
# Display the resulting frame
cv.imshow('myCamera', frame)
if cv.waitKey(1) == ord('q'):
break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
保存视频:
#是从摄像头中捕获视频,沿水平方向旋转每一帧并保存它
import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv.VideoWriter_fourcc(*'XVID')
# ourCC 码以下面的格式传给程序,
# 以 MJPG 为例:cv.VideoWriter_fourcc('M','J','P','G')或者 cv.VideoWriter_fourcc(*'MJPG')。
out = cv.VideoWriter('output.avi', fourcc, 20.0, (640, 480))
while cap.isOpened():
ret, frame = cap.read()
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
frame = cv.flip(frame, 0)
# write the flipped frame
out.write(frame)
cv.imshow('frame', frame)
if cv.waitKey(1) == ord('q'):
break
# Release everything if job is finished
cap.release()
out.release()
cv.destroyAllWindows()
画线:
import numpy as np
import cv2 as cv
# Create a black image
#((h,w,几层),np采用八进制)
img = np.zeros((512,512,3), np.uint8)
# Draw a diagonal blue line with thickness of 5 px
#(名字,起始点,终止点,颜色(opencv中是BGR),宽度)
cv.line(img,(0,0),(511,511),(255,0,0),5)
cv.imshow('img', img)
cv.waitKey(0)
画矩形:
import numpy as np
import cv2 as cv
# Create a black image
#((h,w,几层),np采用八进制)
img = np.zeros((512,512,3), np.uint8)
#(名字,左上坐标,右下坐标,颜色(BGR),框线宽度)
#左上角为(0,0)点,向右x正方向,向下y正方向
cv.rectangle(img,(0,0),(100,100),(0,255,0),3)
cv.imshow('img', img)
cv.waitKey(0)
画圆:
import numpy as np
import cv2 as cv
# Create a black image
#((h,w,几层),np采用八进制)
img = np.zeros((512,512,3), np.uint8)
#(名字,圆心,半径,颜色(BGR),框线厚度(-1及填鸭))
cv.circle(img,(100,100), 66, (0,0,255), -1)
cv.imshow('img', img)
cv.waitKey(0)
画椭圆:
import numpy as np
import cv2 as cv
# Create a black image
#((h,w,几层),np采用八进制)
img = np.zeros((512,512,3), np.uint8)
#(名字,中心点,长轴短轴长度,整体沿逆时针方向旋转角度,
# 起始角度,终止角度(是不是完成椭圆),颜色,线框宽度
cv.ellipse(img,(256,256),(100,50),0,0,180,255,-1)
cv.imshow('img', img)
cv.waitKey(0)
画多边形:
import numpy as np
import cv2 as cv
# Create a black image
#((h,w,几层),np采用八进制)
img = np.zeros((512,512,3), np.uint8)
#各个顶点坐标,数据类型int32
pts = np.array([[10,5],[20,30],[70,20],[50,10]], np.int32)
pts = pts.reshape((-1,1,2))
cv.polylines(img,[pts],True,(0,255,255))
cv.imshow('img', img)
cv.waitKey(0)
写字:
import numpy as np
import cv2 as cv
# Create a black image
#((h,w,几层),np采用八进制)
img = np.zeros((500,500,3), np.uint8)
#调用函数,写的字赋给font
font = cv.FONT_HERSHEY_SIMPLEX
#(名字,要写的文字,位值,字,字体大小,颜色,字体笔画宽度
# cv.LINE_AA(字体类型)
cv.putText(img,'OpenCV',(10,500), font, 8,(255,255,255),2,cv.LINE_AA)
cv.imshow('img', img)
cv.waitKey(0)
思考题:
Opencv库与Matlab、halcon的区别?
Opencv开源计算机图像库,科研和商用,侧重计算机视觉领域
Matlab比较慢
halcon收费非开源,侧重机器视觉领域
为什么是import cv2?
cv2中的‘2’代表的不是OpenCV的版本,OpenCV是基于C/C++的,”cv”表示底层使用的是C API,”cv2”表示使用的是C++API。这主要是一个历史遗留问题,是为了保持向后兼容性。
在显示完之后,用不用cv.destroyWindow()有什么区别?
终止对话框
png图片格式和jpg图片格式有什么区别?
jpg是二进制24位,有损压缩,持续压缩画质会变差
gif是二进制8位的,支持动图
png,有24位和8位两种,支持透明格式,无损
练习题:
同时显示两张不同分辨率的图片,对比他们的大小;
img1 = cv.imread("picture\love.jpg")
img2 = cv.imread("picture\me.jpg")
print(img1.shape)
height = img1.shape[0]
weight = img1.shape[1]
channels = img1.shape[2]
print("weight : %s, height : %s, channel : %s" %(weight, height, channels))
print(img2.shape)
height = img2.shape[0]
weight = img2.shape[1]
channels = img2.shape[2]
print("weight : %s, height : %s, channel : %s" %(weight,height,channels))
cv.waitKey(0)
"""
(1200, 1920, 3)
weight : 1920, height : 1200, channel : 3
(1440, 1920, 3)
weight : 1920, height : 1440, channel : 3
"""
使用Opencv,测试一下你电脑摄像头的分辨率和帧率是多少;
import cv2 as cv
cap = cv.VideoCapture(0)
if not cap.isOpened():
print("Cannot open camera.")
while True:
ret,frame = cap.read()
if not ret:
print("Can't receive frame.")
break
cv.imshow("myCamera",frame)
if cv.waitKey(1) == ord("q"):
break
print(frame.shape)
cap.release()
cv.destroyAllWindows()
#(480, 640, 3)
利用电脑摄像头从外界拍摄一幅自己的图像,添加圆(或其他图形)给自己打码,图片右下角添加自己的网名和时间。
import cv2 as cv
import time
cap = cv.VideoCapture(0)
if not cap.isOpened():
print("Capture is not open.")
exit(0)
#退出程序
else:
ret,frame = cap.read()
cap.release()
if not ret:
print("Can't receive frame.")
exit(0)
cv.circle(frame,(100,100),66,(0,0,255),1)
cv.putText(frame, 'ronaldo '+time.asctime(), (350, 400), cv.LINE_AA, 0.5, (255, 255, 255))
#cv.putText(frame, 'ronaldo' + time.asctime(time.localtime(time.time())), (350, 450), cv.FONT_HERSHEY_SIMPLEX, 0.5,(255, 255, 255))
cv.imshow("myPicture", frame)
cv.waitKey(0)
cv.destroyAllWindows()