我想在图像上绘制等高线,只有当它满足以下条件时,1)如果等高线的X坐标小于或等于600 2)如果等高线的Y坐标小于或等于240 3)如果等高线的面积大于或等于900 但我看到的输出是这样的 不是 满足这些条件 在所有 (甚至还加了一段代码来画线,也不显示线了)
源代码 :
import os
import re
import cv2 # opencv library
import numpy as np
from os.path import isfile, join
import matplotlib.pyplot as plt
# get file names of the frames
col_frames = os.listdir('persons/')
# sort file names
col_frames.sort(key=lambda f: int(re.sub(r'\D', '', f)))
# empty list to store the frames
col_images=[]
for i in col_frames:
# read the frames
img = cv2.imread('persons/'+i)
# append the frames to the list
col_images.append(img)
# Taking 66th frame
i = 66
# convert the frames to grayscale
grayA = cv2.cvtColor(col_images[i], cv2.COLOR_BGR2GRAY)
grayB = cv2.cvtColor(col_images[i+1], cv2.COLOR_BGR2GRAY)
diff_image = cv2.absdiff(grayB, grayA)
cv2.GaussianBlur(diff_image, (5,5), 0)
# perform image thresholding
ret, thresh = cv2.threshold(diff_image, 30, 255, cv2.THRESH_BINARY)
# apply image dilation
kernel = np.ones((20,20),np.uint8)
dilated = cv2.dilate(thresh,kernel,iterations = 1)
contours,_ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
valid_cntrs = []
for i,cntr in enumerate(contours):
x,y,w,h = cv2.boundingRect(cntr)
print(cv2.contourArea(cntr))
if ((x <= 600) & (y <= 240)) & (cv2.contourArea(cntr) >= 900):
valid_cntrs.append(cntr)
#Count of Contours
print('length of contours',len(contours))
# count of discovered contours
print('length of valid contours',len(valid_cntrs))
dmy = col_images[67].copy()
cv2.line(dmy, (0, 240),(800,240),(100, 255, 255))
cv2.drawContours(dmy, valid_cntrs, -1, (127,200,0), 2)
plt.imshow(dmy)
plt.show()
产出 :
49631.0
65.5
32.5
15.0
654.0
854.5
length of contours 6
length of valid contours 1
<Also the output image above>
根据你的图像和输出,实际上似乎是可行的.你可能不知道边界框的x和y坐标是矩形的左上角.如果你想根据轮廓的中间点来验证轮廓,用这段代码替换验证部分。
for i,cntr in enumerate(contours):
x,y,w,h = cv2.boundingRect(cntr)
mid_x = x + w / 2.0
mid_y = y + h / 2.0
print(cv2.contourArea(cntr))
if ((mid_x <= 600) & (mid_y <= 240)) & (cv2.contourArea(cntr) >= 900):
valid_cntrs.append(cntr)
要检查等高线的右下角,请用以下代码代替:
for i,cntr in enumerate(contours):
x,y,w,h = cv2.boundingRect(cntr)
rb_x = x + w
rb_y = y + h
print(cv2.contourArea(cntr))
if ((rb_x <= 600) & (rb_y <= 240)) & (cv2.contourArea(cntr) >= 900):
valid_cntrs.append(cntr)