opencv读取图片cv2格式转换

1、字节转字符串:

def bytes2str(b):
    return base64.b64encode(b).decode()

2、字符串转字节:

def str2bytes(s):
    return base64.b64decode(s.encode())

3、cv2格式转为字符串:

        image_encode = cv2.imencode('.jpg', np.asarray(img_raw))[1]
        image_str = str(base64.b64encode(image_encode))[2:]

4、字符串转cv2:

def str2np_cv2(img_str):
    img_bytes = base64.b64decode(img_str)
    img_np = np.frombuffer(img_bytes, dtype=np.uint8)
    img_np_cv2 = cv2.imdecode(img_np, cv2.IMREAD_COLOR)
    return img_np_cv2

5、根据人脸坐标定位,画框:

    if score <0.8:
        text="Not clear"
        color=(0,0,255)
    else:
        text="clear"
        color=(0,255,0)
    cv2.rectangle(img_np_cv2, (int(ymin), int(xmin)), (int(ymax), int(xmax)),color, 2)
    cv2.putText(img_np_cv2, "%s: %.2f" % (text, score), (int(xmin), int(ymin)), cv2.FONT_HERSHEY_SIMPLEX,1,color,2)
    #最后一个表示字体粗细,color表示字体颜色,1表示字体大小。

    cv2.namedWindow('image', 0)
    cv2.resizeWindow("image", 600, 600)
    cv2.imshow('image', img_np_cv2)
    cv2.waitKey(waitkey)

6、利用本地摄像头获取视频并显示:

def run_on_video(video_path, output_video_name, conf_thresh):
    cap = cv2.VideoCapture(video_path)
    height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
    width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
    fps = cap.get(cv2.CAP_PROP_FPS)
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    # writer = cv2.VideoWriter(output_video_name, fourcc, int(fps), (int(width), int(height)))
    total_frames = cap.get(cv2.CAP_PROP_FRAME_COUNT)
    if not cap.isOpened():
        raise ValueError("Video open failed.")
        return
    status = True
    idx = 0
    
    while status:
        start_stamp = time.time()
        status, img_raw = cap.read()
        img_raw = cv2.cvtColor(img_raw, cv2.COLOR_BGR2RGB)
        read_frame_stamp = time.time()
        if (status):
            inference(img_raw,
                      conf_thresh,
                      iou_thresh=0.5,
                      target_shape=(360, 360),
                      draw_result=True,
                      show_result=False)

            cv2.imshow('image', img_raw[:, :, ::-1])
            cv2.waitKey(1)
            inference_stamp = time.time()
            # writer.write(img_raw)
            write_frame_stamp = time.time()
            idx += 1
            print("%d of %d" % (idx, total_frames))
            print("read_frame:%f, infer time:%f, write time:%f" % (read_frame_stamp - start_stamp,
                                                                   inference_stamp - read_frame_stamp,
                                                                   write_frame_stamp - inference_stamp))

7、waitkey

cv2.waitKey(1) #不需要点击
cv2.waitKey(0)#点击之后,才可以结束



    原文作者:OnTheOurWay
    原文地址: https://blog.csdn.net/weixin_42726887/article/details/122105543
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞