# 调用摄像头 # capture=cv2.VideoCapture("1.mp4") #-------------------------------------# capture = cv2.VideoCapture(0) fps = 0.0 while (True): t1 = time.time() # 读取某一帧 ref, frame = capture.read() # 格式转变,BGRtoRGB frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # 转变成Image frame = Image.fromarray(np.uint8(frame)) # 进行检测 frame = np.array(pspnet.detect_image(frame)) # RGBtoBGR满足opencv显示格式 frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) fps = (fps + (1. / (time.time() - t1))) / 2 print("fps= %.2f" % (fps)) frame = cv2.putText(frame, "fps= %.2f" % (fps), (0, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) cv2.imshow("video", frame) c = cv2.waitKey(30) & 0xff if c == 27: capture.release() break
2、如果想要保存,利用r_image.save("img.jpg")即可保存。 3、如果想要原图和分割图不混合,可以把blend参数设置成False。 4、如果想根据mask获取对应的区域,可以参考detect_image中,利用预测结果绘图的部分。 seg_img = np.zeros((np.shape(pr)[0],np.shape(pr)[1],3)) for c in range(self.num_classes): seg_img[:, :, 0] += ((pr == c)*( self.colors[c][0] )).astype('uint8') seg_img[:, :, 1] += ((pr == c)*( self.colors[c][1] )).astype('uint8') seg_img[:, :, 2] += ((pr == c)*( self.colors[c][2] )).astype('uint8') ''' import tensorflow as tf from PIL import Image from pspnet import Pspnet gpus = tf.config.experimental.list_physical_devices(device_type='GPU') for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) pspnet = Pspnet() while True: img = input('Input image filename:') try: image = Image.open(img) except: print('Open Error! Try again!') continue else: r_image = pspnet.detect_image(image) r_image.show()
4、如果想根据mask获取对应的区域,可以参考detect_image函数中,利用预测结果绘图的部分,判断每一个像素点的种类,然后根据种类获取对应的部分。 seg_img = np.zeros((np.shape(pr)[0],np.shape(pr)[1],3)) for c in range(self.num_classes): seg_img[:, :, 0] += ((pr == c)*( self.colors[c][0] )).astype('uint8') seg_img[:, :, 1] += ((pr == c)*( self.colors[c][1] )).astype('uint8') seg_img[:, :, 2] += ((pr == c)*( self.colors[c][2] )).astype('uint8') ''' while True: img = input('Input image filename:') try: image = Image.open(img) except: print('Open Error! Try again!') continue else: r_image = pspnet.detect_image(image) r_image.show() elif mode == "video": capture = cv2.VideoCapture(video_path) if video_save_path != "": fourcc = cv2.VideoWriter_fourcc(*'XVID') size = (int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))) out = cv2.VideoWriter(video_save_path, fourcc, video_fps, size) ref, frame = capture.read() if not ref: raise ValueError("未能正确读取摄像头(视频),请注意是否正确安装摄像头(是否正确填写视频路径)。") fps = 0.0