yolov8 pycharm运行(predict,不用command line)

yolov8就不介绍了,见主页

这里说下用pycharm运行。
代码参考segment页

from ultralytics import YOLO

# Load a model
model = YOLO('yolov8n-seg.pt')  # load an official model

# Predict with the model
results = model('test_img.jpg')  # predict on an image

不通过command line,结果就只会显示predict时间和几个坐标。
并没有显示图片,也没有保存输出图片。

在这里插入图片描述

results里面的数据如下:

在这里插入图片描述

难道需要自己把box画出来?
不需要自己去写后处理,model里面自带的,现在来把它找出来。

ultralytics/yolo/engine/predictor.py的BasePredictor中,看到了predict的流程,
可以看到,如果args.save或者args.show为True, 就会保存结果,
args.show和self.plotted_img同时为True, 就会显示结果.

如果用Command line执行,show和save是直接设置的,那么pycharm在哪里设置?
(在Run->Edit Configurations的parameters里面设置show=True save=True并没什么用)。

class BasePredictor:
    def stream_inference(self, source=None, model=None):
    ...
        for batch in self.dataset:
            ...
            # Preprocess
            with profilers[0]:
                im = self.preprocess(im0s)

            # Inference
            with profilers[1]:
                preds = self.model(im, augment=self.args.augment, visualize=visualize)

            # Postprocess
            with profilers[2]:
                self.results = self.postprocess(preds, im, im0s)
            self.run_callbacks('on_predict_postprocess_end')

            # Visualize, save, write results
           ...
                if self.args.verbose or self.args.save or self.args.save_txt or self.args.show:
                    s += self.write_results(i, self.results, (p, im, im0))

                if self.args.show and self.plotted_img is not None:
                    self.show(p)

                if self.args.save and self.plotted_img is not None:
                    self.save_preds(vid_cap, i, str(self.save_dir / p.name))

先看self.plotted_img怎么设置,
可以看到只要show或save任意一个为True,它就不是None.
下面问题简化到了在哪里设置show和save.

    def write_results(self, idx, results, batch):
        if self.args.save or self.args.show:  # Add bbox to image
            ...
            self.plotted_img = result.plot(**plot_args)

在下面的get_cfg中,找到了有一个cfg文件,

def get_cfg(cfg: Union[str, Path, Dict, SimpleNamespace] = DEFAULT_CFG_DICT, overrides: Dict = None):
    """
    Load and merge configuration data from a file or dictionary.

    Args:
        cfg (str) or (Path) or (Dict) or (SimpleNamespace): Configuration data.
        overrides (str) or (Dict), optional: Overrides in the form of a file name or a dictionary. Default is None.

    Returns:
        (SimpleNamespace): Training arguments namespace.
    """
    cfg = cfg2dict(cfg)

找到设置文件为ultralytics/yolo/cfg/default.yaml
把里面的show改为True.
就会通过show函数。

    def show(self, p):
        """Display an image in a window using OpenCV imshow()."""
        im0 = self.plotted_img
        if platform.system() == 'Linux' and p not in self.windows:
            self.windows.append(p)
            cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)  # allow window resize (Linux)
            cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
        cv2.imshow(str(p), im0)
        cv2.waitKey(500 if self.batch[3].startswith('image') else 1)  # 1 millisecond

函数中,图片只会显示0.5s,video的话每张图片会显示1ms.
也就是说,基本上显示一瞬间就没了。
可以在show函数中改时间,或者保存图片。
但是现在不希望改show函数,想通过args.save解决。

default.yaml中已经有save为True, 但是仍然不保存图片。
于是找到cfg变量,看到save仍然为False,肯定是在哪里被覆盖掉了。

class YOLO:
    def predict(self, source=None, stream=False, **kwargs):
        if not is_cli:
            overrides['save'] = kwargs.get('save', False)  # do not save by default if called in Python

这里明确了,如果不是command line执行的,就不会保存,设置了save为True也会被改成False.
把这里改一下,运行时就会有一个新的文件夹runs, 里面有保存的图片。

请添加图片描述

猜你喜欢

转载自blog.csdn.net/level_code/article/details/130708147