1.OpenCV是什么?
- 开源——OpenCV是开源的,并根据BSD3条款许可发布
- 优化——OpenCV是高度优化的库,专注于实时应用程序
- 跨平台——拥有C++,Python,Java API,支持Linux,Mac OS,Windows,iOS和Android
2.图片的基本认知
图像在视觉感受上分为灰度图和彩色图,灰度图只有1个通道, 彩色图最少有3个通道,这是因为存在一种PNG格式的彩色图,这种图还有一个α通道,这个α通道管着图像的透明度
一个像素点的位置:
一个像素点的值:
point的值为[207 220 243]
,在OpenCV中分别代表Blue通道,Green通道,Red通道的值,即[207 220 243]=[Blue=207 Green=220 Red=243]
3.图片基础操作
- 导入库
import cv2
- 打开
img = cv2.imread("star.png")
- 判断图像是否为空,即读取图像错误,仅限与OpenCV可以读取的图片格式
if img.size != 0:
print("Image File is OK")
else:
print("Image File may be broken, please check the image file or the path of the image file")
- 显示
cv2.imshow("img", img)
结果:
- 保存
cv2.imwrite("new_star.png", img)
- 截取
point1_x, point1_y = 128,128
point2_x, point2_y = 320, 320
area = img[point1_y:point2_y, point1_x:point2_x]
- 画框
cv2.rectangle(img, (128, 128), (320, 320), (0, 0, 255), 1)
# cv2.rectangle(图片,矩形左上角的坐标位置,矩形右下角的坐标位置,颜色,线的粗细)
- 画点或圆
cv2.circle(img,(128, 128), 4, (0, 0, 255), -1)
cv2.circle(img,(320, 320), 4, (255, 0, 0), -1)
# cv2.circle(图片,圆心位置,圆的半径,圆的颜色,圆形轮廓的粗细(如果为正)负数(-1)表示要绘制实心圆,圆边界的类型,中心坐标和半径值中的小数位数)
- 放置文本
cv2.putText(img, "point 1", (128 + 4, 128), cv2.FONT_HERSHEY_COMPLEX, 0.50, (255, 0, 0), 1)
cv2.putText(img, "point 2", (320 + 4, 320), cv2.FONT_HERSHEY_COMPLEX, 0.50, (0, 0, 255), 1)
# cv2.putText(图片,文本,位置,文本字体,文本大小,文本颜色)
显示:
- 灰度化
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)