【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)
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]
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() #释放窗口
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”等
这里一定要注意的是,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)