Not able to stop the video stream and thereby unable to save the dataset

I have successfully run the code and record the skip count here, however inspite of pressing the q key I am not able to close the video stream which was working earlier to when I added that np.save portion.

This is my code :

import cv2
import numpy as np

#Initialising the camera
cap = cv2.VideoCapture(0)

Face detection

face_cascade = cv2.CascadeClassifier(‘C:\Users\Charu Anant Rajput\Desktop\Python\opencv\data\haarcascades\haarcascade_frontalface_alt.xml’)

skip = 0;
face_data = []
dataset_path = ‘./data/’

file_name = input('Enter the name of the person whose face you are scanning : ')

while True:
ret,frame = cap.read() #reading from the frame

if ret==False:
	continue

gray_frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)


faces = face_cascade.detectMultiScale(frame,1.3,5)
#now sorting according to the area
faces = sorted(faces,key=lambda f:f[2]*f[3])

#iterating over the face(pick the last face because it is largest in terms of area(f[2]*f[3]))
for face in faces[-1:]:
	x,y,w,h = face
	cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,255),2)

	#Extract the region of interest
	offset = 10;
	face_section = frame[y-offset:y+h+offset,x-offset:x+w+offset]
	face_section = cv2.resize(face_section,(100,100))

	skip+=1
	#Storing the 10th face
	if skip%10==0:
		face_data.append(face_section)
		print(len(face_data))



cv2.imshow("Frame",frame)
#showing the face section
cv2.imshow("Face section",face_section)

#wait for the user input - q, then you will stop the loop
key_pressed = cv2.waitKey(1) & 0xFF

if key_pressed == ord('q'):
	break

#Convert the normal array into numpy array
face_data = np.asarray(face_data)
face_data = face_data.reshape((face_data.shape[0],-1))
print(face_data.shape)

#Save this data into the file system
np.save(dataset_path+file_name+’.npy’,face_data)
print(“Data Successfull saved at” +dataset_path+file_name+’.npy’)

cap.release()
cap.destroyAllWindows()

Please guide further.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.