opencv(python)-读取图片、视频,轮廓检测

【2019.1.14更新】:
使用opencv读取图片,画框,标注文本

import cv2
a = cv2.imread('David/img/0471.jpg')
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(a,'#471',(20,20),font,0.5,(0,0,255),1)
cv2.rectangle(a,(131,83),(131+41,83+52),(0,255,0),2)
cv2.imshow('demo',a)
cv2.waitKey(0)

在这里插入图片描述

opencv的使用(python)

  1. 读取图片
image=cv2.imread('F:\\demo\\123.jpg')
print(image.shape) #(300, 533, 3)读进来的尺寸是(高度,长度,通道)
print(np.asarray(image.shape[:2][::-1])) #[533 300] 
#解析:[:2]表示只取前两维,[::-1]表示逆序,相当于得到了长度,高度。

opencv的cv2.imread()读取的是BGR格式图像,需要转换成RGB,这里列出两种转换成RGB的方法~

img=cv2.imread('F:\\demo\\123.jpg')
plt.imshow(img)
plt.show()   
#【方法1】
b,g,r = cv2.split(img)
img2 = cv2.merge([r,g,b])
plt.imshow(img2)
plt.show()
#【方法2】
image = img[:, :, ::-1]
  1. 读取视频
import cv2
videoCapture = cv2.VideoCapture('demo.avi')
fps = videoCapture.get(cv2.CAP_PROP_FPS) #获取帧率
size = (int(videoCapture.get(cv2.CAP_PROP_FRAME_WIDTH)),  #获取视频尺寸
        int(videoCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
while(1):
    ret, frame = videoCapture.read() #读帧
    cv2.imshow("capture", frame)  #显示视频
    if cv2.waitKey(100) & 0xFF == ord('q'): #按q键退出
        break
videoCapture.release()  
cv2.destroyAllWindows() #释放窗口
  1. 读取视频帧,并转换成视频流
im_dir = 'F:\\demo\\car' #图片路径
video_dir = 'F:\\demo\\out.avi' #输出视频路径
fps = 30  #帧率
num = 284 #图片数 
img_size = (1104,622) #图片尺寸

fourcc = cv2.VideoWriter_fourcc('M','J','P','G') #opencv3.0
videoWriter = cv2.VideoWriter(video_dir, fourcc, fps, img_size)

for i in range(1,num):
    im_name = os.path.join(im_dir, str(i).zfill(8)+'.jpg')
    frame = cv2.imread(im_name)
    videoWriter.write(frame)
    #print(im_name)

videoWriter.release()
print('finish')
#【注意】:图片命名格式为“00000001.jpg”,“00000002.jpg”等

opencv中的cv2.findContours()边缘检测函数

这里一定要注意的是,opencv2和opencv3的用法不一样!!
https://blog.csdn.net/caicai2526/article/details/79637630

import cv2

img = cv2.imread('/home/桌面/1.jpeg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

image,contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
print(len(hierarchy))
cv2.drawContours(img, contours, -1, (0, 0, 255), 3)

cv2.imshow("img", img)
cv2.waitKey(0)

如果想要用最小外接矩形框来填充图像

for i in range(len(contours)):
    bounding_box = cv2.minAreaRect(contours[i])  #得到最小外接矩形的(中心(x,y), (,), 旋转角度)
    bounding_box = cv2.boxPoints(bounding_box)  #  获取最小外接矩形的4个顶点

    bounding_box = np.array(bounding_box, dtype=np.int32)
    bounding_box = bounding_box.reshape([1, bounding_box.shape[0], bounding_box.shape[1]])

    cv2.fillPoly(binary, bounding_box, 255)
cv2.imshow("a",binary)
cv2.waitKey(0)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值