我在给定的空间内有2只老鼠。我想将其中一个命名为A,将另一个命名为B。但是,我很难分别命名它们。我的代码似乎同时标记了老鼠A和B(“ A”和“ B”相互重叠)。我已附上图片以供参考。有没有办法分开两只老鼠的标签?
import cv2
import numpy as np
import time
import imutils
import pandas as pd
COLOR = {'red': (0, 0, 255),
'green': (102, 255, 0),
'blue': (236, 56, 20),
'yellow': (0, 127, 255),
'black': (0, 0, 0),
'white': (255, 255, 255)}
# Input Video
cap = cv2.VideoCapture('video.mp4')
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
# Video Saving Settings
# maskVideo = cv2.VideoWriter(
# '/Users/vpara/Desktop/Videos/mask.mp4', fourcc, 24.0, size, isColor=False)
# edgeVideo = cv2.VideoWriter(
# '/Users/vpara/Desktop/edge.mp4', fourcc, 24.0, size, isColor=False)
# hullVideo = cv2.VideoWriter(
# '/Users/vpara/Desktop/hull.mp4', fourcc, 24.0, size, isColor=True)
mouse1 = []
mouse2 = []
mouse3 = []
mouse4 = []
times = []
while (1):
ret, frame = cap.read()
if ret:
# frame = cv2.resize(frame, (500, 630))
# Bilateral Filter to Remove Noise
blur = cv2.bilateralFilter(frame, 15, 100, 100)
# Add Mask that only shows values within range
mask = cv2.inRange(blur, (0, 0, 0, 0), (150, 150, 80, 0))
# Canny Edge Detection
edge = cv2.Canny(mask, 80, 150)
contours = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
contours = imutils.grab_contours(contours)
hull = []
for i in range(len(contours)):
# create convex hull object for each contour
hull.append(cv2.convexHull(contours[i], False))
# returns a new array of the given shape, filled with zeroes
drawing = np.zeros((mask.shape[0], mask.shape[1], 3), np.uint8)
# draw contours and hull points
for i in range(len(contours)):
# draw new convex hull contour
cv2.drawContours(drawing, hull, i,
COLOR['blue'], 1, 8)
# draw edge detected contour
cv2.drawContours(drawing, contours, i, COLOR['green'], 1, 8)
# Drawing the center of each contour
position = [1]
for c in contours:
# compute the center of the contour
M = cv2.moments(c)
if M["m00"] != 0:
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
new = [cX, cY]
cv2.putText(mask,'A', (cX,cY),cv2.FONT_HERSHEY_DUPLEX, 0.6, COLOR['green'])
cv2.putText(edge,'A', (cX,cY),cv2.FONT_HERSHEY_DUPLEX, 0.6, COLOR['green'])
cv2.putText(drawing,'A', (cX,cY),cv2.FONT_HERSHEY_DUPLEX, 0.6, COLOR['green'])
cv2.putText(mask,'B', (cX,cY),cv2.FONT_HERSHEY_DUPLEX, 0.6, COLOR['green'])
cv2.putText(edge,'B', (cX,cY),cv2.FONT_HERSHEY_DUPLEX, 0.6, COLOR['green'])
cv2.putText(drawing,'B', (cX,cY),cv2.FONT_HERSHEY_DUPLEX, 0.6, COLOR['green'])
# draws arrow from centroid to highest point of contour
extTop = tuple(c[c[:, :, 1].argmin()][0])
arrow = cv2.arrowedLine(drawing, (cX,cY), extTop, COLOR['yellow'], 2, tipLength=0.3)
# draws centroid
cv2.circle(drawing, (cX, cY), 3, COLOR['blue'], -1)
position.append(new)
# print(position)
mouse1.append(position[0])
mouse2.append(position[1])
mouse3.append([])
mouse4.append([])
if len(contours) > 2:
if len(contours) == 3:
mouse3.append(position[2])
else:
mouse4.append(position[3])
seconds = str('%.0f s' % (cap.get(cv2.CAP_PROP_POS_MSEC) / 1000.))
times.append(seconds)
# Display time
cv2.putText(mask, 'Time: ' + seconds, (5, 20),
cv2.FONT_HERSHEY_DUPLEX, 0.5, COLOR['white'])
cv2.putText(edge, 'Time: ' + seconds, (5, 20),
cv2.FONT_HERSHEY_DUPLEX, 0.5, COLOR['white'])
cv2.putText(drawing, 'Time: ' + seconds, (5, 20),
cv2.FONT_HERSHEY_DUPLEX, 0.5, COLOR['white'])
cv2.imshow("mask", mask)
cv2.imshow("edge", edge)
cv2.imshow("hull", drawing)
else:
cap.release()
break
k = cv2.waitKey(5) & 0xFF
if (k == 113): # press q to quit
break
cv2.destroyAllWindows()
您可以创建标签列表,并且仅对列表中的相关标签使用putText
。
下面的代码示例中的大多数修改是为了删除您发布的图像的假象。
代码示例,假设只有两个轮廓,并且标签列表为('A', 'B')
。
这里是一个与您发布的图像一起使用的代码示例:
import cv2
import numpy as np
import time
import imutils
import pandas as pd
COLOR = {'red': (0, 0, 255),
'green': (102, 255, 0),
'blue': (236, 56, 20),
'yellow': (0, 127, 255),
'black': (0, 0, 0),
'white': (255, 255, 255)}
frame = cv2.imread('mice.jpg', cv2.IMREAD_GRAYSCALE)
frame = frame[70:-1, 1:-1]
# Input Video
#cap = cv2.VideoCapture('video.mp4')
#size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
# int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
#fourcc = cv2.VideoWriter_fourcc(*'DIVX')
# Video Saving Settings
# maskVideo = cv2.VideoWriter(
# '/Users/vpara/Desktop/Videos/mask.mp4', fourcc, 24.0, size, isColor=False)
# edgeVideo = cv2.VideoWriter(
# '/Users/vpara/Desktop/edge.mp4', fourcc, 24.0, size, isColor=False)
# hullVideo = cv2.VideoWriter(
# '/Users/vpara/Desktop/hull.mp4', fourcc, 24.0, size, isColor=True)
mouse1 = []
mouse2 = []
mouse3 = []
mouse4 = []
times = []
# frame = cv2.resize(frame, (500, 630))
# Bilateral Filter to Remove Noise
#blur = cv2.bilateralFilter(frame, 15, 100, 100)
# Add Mask that only shows values within range
#mask = cv2.inRange(blur, 0, 150)
mask = cv2.inRange(frame, 150, 255)
#Remove the text (just for tresing)...
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5)));
# Canny Edge Detection
edge = cv2.Canny(mask, 80, 150)
#cv2.imshow("mask", mask)
#cv2.imshow("edge", edge)
#cv2.waitKey(0)
contours = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
contours = imutils.grab_contours(contours)
hull = []
for i in range(len(contours)):
# create convex hull object for each contour
hull.append(cv2.convexHull(contours[i], False))
# returns a new array of the given shape, filled with zeroes
drawing = np.zeros((mask.shape[0], mask.shape[1], 3), np.uint8)
#Convert to BGR (just for drawing)
mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
edge = cv2.cvtColor(edge, cv2.COLOR_GRAY2BGR)
# draw contours and hull points
for i in range(len(contours)):
# draw new convex hull contour
cv2.drawContours(drawing, hull, i,
COLOR['blue'], 1, 8)
# draw edge detected contour
cv2.drawContours(drawing, contours, i, COLOR['green'], 1, 8)
labels = ('A', 'B') # Holds labels
# Drawing the center of each contour
position = [1]
# Iterate contours and labels
for c, label in zip(contours, labels):
# compute the center of the contour
M = cv2.moments(c)
if M["m00"] != 0:
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
new = [cX, cY]
cv2.putText(mask, label, (cX,cY),cv2.FONT_HERSHEY_DUPLEX, 0.6, COLOR['green'])
cv2.putText(edge, label, (cX,cY),cv2.FONT_HERSHEY_DUPLEX, 0.6, COLOR['green'])
cv2.putText(drawing, label, (cX,cY),cv2.FONT_HERSHEY_DUPLEX, 0.6, COLOR['green'])
# draws arrow from centroid to highest point of contour
extTop = tuple(c[c[:, :, 1].argmin()][0])
arrow = cv2.arrowedLine(drawing, (cX,cY), extTop, COLOR['yellow'], 2, tipLength=0.3)
# draws centroid
cv2.circle(drawing, (cX, cY), 3, COLOR['blue'], -1)
position.append(new)
# print(position)
mouse1.append(position[0])
mouse2.append(position[1])
mouse3.append([])
mouse4.append([])
if len(contours) > 2:
if len(contours) == 3:
mouse3.append(position[2])
else:
mouse4.append(position[3])
cv2.imshow("mask", mask)
cv2.imshow("edge", edge)
cv2.imshow("hull", drawing)
cv2.waitKey(0)
cv2.destroyAllWindows()
结果: