_, img = cap.read() zeros_image = np.zeros((img.shape[0], img.shape[1], 1), np.uint8)
img_ycrcb = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
blur = cv2.GaussianBlur(img_ycrcb, (11, 11), 0)
skin_ycrcb_min = np.array((0, 0, 140))
skin_ycrcb_max = np.array((65, 253, 255))
skin_ycrcb_min = np.array((0, 0, 180))
skin_ycrcb_max = np.array((140, 255, 255))
mask = cv2.inRange(blur, skin_ycrcb_min, skin_ycrcb_max)
contours, hierarchy = cv2.findContours(
mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2:]
valid_cntrs = []
for i, cnt in enumerate(contours):
x, y, w, h = cv2.boundingRect(cnt)
area = cv2.contourArea(cnt)
cX = int(x (w/2))
cY = int(y (h/2))
if (x <= 600) & (y >= 300) & (y <= 455) & (area > 900):
valid_cntrs.append(cnt)
cv2.putText(img, str(f'{cX},{cY}'), (cX, cY), cv2.FONT_HERSHEY_SIMPLEX,
1, (255, 0, 0), 2, cv2.LINE_AA)
cv2.rectangle(zeros_image, (x, y), (x w, y h), (255),
thickness=cv2.FILLED)
mask1 = np.zeros((zeros_image.shape[0], zeros_image.shape[1], 1), np.uint8)
mask_result = cv2.bitwise_or(zeros_image, zeros_image, mask=Sensor1.mask)
white_cell_number = np.sum(mask_result == 255)
sensor_rate = white_cell_number/Sensor1.full_mask_area
sensor_rate prints out values between 0.85 to 31 or less than 0.85
CodePudding user response:
Original code:
# detect whether there is car via bitwise_and
mask1=np.zeros((zeros_image.shape[0],zeros_image.shape[1],1),np.uint8)
mask_result=cv2.bitwise_or(zeros_image,zeros_image,mask=Sensor1.mask)
white_cell_number=np.sum(mask_result==255)
# detect to control whether car is passing under the red line sensor
sensor_rate=white_cell_number/Sensor1.full_mask_area
white_cell_number
is the number of white pixels in mask_result
.
sensor_rate
is the ratio of white pixels vs the number of total pixels in Sensor1.full_mask_area
.
Looking further up int he code:
class Sensor:
def __init__(self,kordinat1,kordinat2,frame_weight,frame_lenght):
self.kordinat1=kordinat1
self.kordinat2=kordinat2
self.frame_weight=frame_weight
self.frame_lenght =frame_lenght
self.mask=np.zeros((frame_weight,frame_lenght,1),np.uint8)*abs(self.kordinat2.y-self.kordinat1.y)
self.full_mask_area=abs(self.kordinat2.x-self.kordinat1.x)
cv2.rectangle(self.mask,(self.kordinat1.x,self.kordinat1.y),(self.kordinat2.x,self.kordinat2.y),(255),thickness=cv2.FILLED)
self.stuation=False
self.car_number_detected=0
video=cv2.VideoCapture("video1.mp4")
ret,frame=video.read()
cropped_image= frame[0:450, 0:450]
fgbg=cv2.createBackgroundSubtractorMOG2()
Sensor1 = Sensor(
Kordinat(1, cropped_image.shape[1] - 35),
Kordinat(340, cropped_image.shape[1] - 30),
cropped_image.shape[0],
cropped_image.shape[1])
Sensor1.full_mask_area
is a rectangle defined by two points.
So sensor_rate
is the fill rate of that rectangle.