#_*_ encoding=utf-8 _*_
import numpy as np
import cv2
img=cv2.imread('leilei.jpg')
imggray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#二值化图片,将灰度图片中>127的像素修改为255(白色)
ret,thresh=cv2.threshold(imggray,127,255,0)
# cv2.imshow('thresh',thresh)
#在二值化图像中找轮廓,参数(输入图像,轮廓检索模式,轮廓近似方法),返回值(原图像,轮廓,轮廓的层析结构——轮廓之间的关系)
#具体返回值含义见https://blog.csdn.net/jjddss/article/details/73527990
image,contours,hierarchy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
# cv2.imshow("image",image)
# print("轮廓的数量:",np.size(contours))
# print("第一个轮廓的所有点的坐标:",contours[0])
# print("hierarchy",hierarchy)
contourlist=[]
#绘制轮廓
for contour in contours:
if cv2.contourArea(contour)>200:
contourlist.append(contour)
#根据最后的参数不同,可以选择填充轮廓,还是
img=cv2.drawContours(image,contourlist,3,(0,255,0),3)
cv2.imshow("img",img)
cv2.waitKey(0)
在这里只将轮廓大于200的进行填充,但效果不咋明显。
这里用到的opencv工具有:
cv2.threshold()
cv2.findContours()
#在二值化图像中找轮廓,参数(输入图像,轮廓检索模式,轮廓近似方法),返回值(原图像,轮廓,轮廓的层析结构——轮廓之间的关系)
#具体返回值含义见https://blog.csdn.net/jjddss/article/details/73527990
cv2.contourArea()
cv2.drawContours()
python代码实现:
#_*_ encoding=utf-8 _*_
import cv2
import numpy as np
vedioFile=r"Fueling.mp4"
frame_x=720
frame_y=964
cap=cv2.VideoCapture(vedioFile)
frontFrame=np.zeros((frame_x,frame_y),np.uint8)
targetImage=np.zeros((frame_x,frame_y),np.uint8)
kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
while cap.isOpened():
ret,frame=cap.read()
frameGray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
# (x,y,w,h)=cv2.boundingRect(frameGray)
# print('x:{},y:{},w:{},h:{}'.format(x,y,w,h))
if frontFrame.sum()==0:
frontFrame=frameGray
else:
#使用opencv的方法计算两帧相减并取绝对值
targetImage=cv2.absdiff(frameGray,frontFrame)
ret,targetImage=cv2.threshold(targetImage,127,255,cv2.THRESH_BINARY)
targetImage=cv2.morphologyEx(targetImage,cv2.MORPH_OPEN,kernel)
targetImage=cv2.morphologyEx(targetImage,cv2.MORPH_CLOSE,kernel)
frontFrame=frameGray
cv2.imshow("targetImage",targetImage)
k=cv2.waitKey(35)&0xFF
if k==ord("q"):
break