On Raspberry Pi, can't use VideoCapture with Pi Camera

Hello,
I am trying to get an image form the pi camera. It is connected via the flex cable, not USB. I am running opencv on a raspberry pi3 with python 3. With the libcam-hello it all works.

If I run this code:

#!/usr/bin/python3
import sys
import cv2
import mediapipe as mp
import math
import time
import os
os.system('clear')

cap = cv2.VideoCapture(0)

print(type(cap))
print(cap.isOpened())
print(int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)))

res, img = cap.read()

cv2.imwrite("/home/pi/test.png", img)

cap.release()
cv2.destroyAllWindows()

I get the output

<class ‘cv2.VideoCapture’>
True
640
Traceback (most recent call last):
File “/home/pi/./bodycam.py”, line 21, in
cv2.imwrite(“/home/pi/test.png”, img)
cv2.error: OpenCV(4.7.0) /io/opencv/modules/imgcodecs/src/loadsave.cpp:783: error: (-215:Assertion failed) !_img.empty() in function ‘imwrite’

So it means that the camera is opend and works but the cap.read() fails. I get the same error from lokal or ssh console. What could this be? Thanks?

Edit: if I try fps = int(cap.get(cv2.CAP_PROP_FPS)) it gives me an error it can not get camera fps.

Edit2: I went in raspi-config and enabled legacy camera support. Now the python works but libcamera-hello cant find the camera any more.