Errors: !_img.empty() in function ‘cv::imwrite’ and (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support

Code :
cap = cv2.VideoCapture(0)
for imgnum in range(number_images):
print(‘Collecting image {}’.format(imgnum))
ret, frame = cap.read()
imgname = os.path.join(IMAGES_PATH,f’{str(uuid.uuid1())}.jpg’)
cv2.imwrite(imgname, frame)
cv2.imshow(‘frame’, frame)
time.sleep(0.5)

if cv2.waitKey(1) & 0xFF == ord('q'):
    break

cap.release()
cv2.destroyAllWindows()

Sometimes I am getting the below error
Collecting image 0

error Traceback (most recent call last)
Cell In[6], line 6
4 ret, frame = cap.read()
5 imgname = os.path.join(IMAGES_PATH,f’{str(uuid.uuid1())}.jpg’)
----> 6 cv2.imwrite(imgname, frame)
7 cv2.imshow(‘frame’, frame)
8 time.sleep(0.5)

error: OpenCV(4.8.0) D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:787: error: (-215:Assertion failed) !_img.empty() in function ‘cv::imwrite’

and sometimes
Collecting image 0

error Traceback (most recent call last)
Cell In[4], line 7
5 imgname = os.path.join(IMAGES_PATH,f’{str(uuid.uuid1())}.jpg’)
6 cv2.imwrite(imgname, frame)
----> 7 cv2.imshow(‘frame’, frame)
8 time.sleep(0.5)
10 if cv2.waitKey(1) & 0xFF == ord(‘q’):

error: OpenCV(4.8.0) D:\a\opencv-python\opencv-python\opencv\modules\highgui\src\window.cpp:1272: error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function ‘cvShowImage’

My video capture device number is also right.

you resolved this issue, i am facing the same issue