Ultralytics YOLO26을 사용한 분석

Ultralytics YOLO26을 사용한 분석은 객체 감지와 트래킹 결과를 실시간 차트로 변환하여, 비디오 프레임마다 객체 수가 어떻게 달라지는지 확인할 수 있게 합니다. 이 가이드에서는 선 그래프, 막대 그래프, 원형 차트, 영역 그래프의 네 가지 데이터 시각화 유형을 다루고, Python 및 CLI 예제를 함께 사용해 유형을 전환하는 방법을 보여줍니다.



시청: Ultralytics로 분석 그래프를 생성하는 방법 | 선 그래프, 막대 그래프, 영역 차트 및 원형 차트

시각적 예시#

선 그래프막대 그래프원형 차트
객체 트래킹을 위한 YOLO 분석 선 그래프감지 수를 나타내는 YOLO 분석 막대 그래프클래스 분포를 나타내는 YOLO 분석 원형 차트

감지 데이터를 시각화해야 하는 이유#

  • 선 그래프는 단기 및 장기 변화를 추적하고 동일한 기간 동안 여러 그룹의 변화를 비교하는 데 적합합니다.
  • 막대 그래프는 다양한 범주의 수량을 비교하고 범주와 수치 간의 관계를 보여주는 데 적합합니다.
  • 원형 차트는 범주 간 비율을 설명하고 전체에서 각 부분이 차지하는 비중을 보여주는 데 효과적입니다.
  • 영역 그래프는 선 그래프 아래쪽을 채워 시간에 따른 클래스별 객체 수를 한눈에 더 쉽게 파악할 수 있게 합니다.

분석 그래프 생성#

비디오를 Analytics 솔루션에 전달하고 analytics_type을 사용해 차트를 선택합니다. 솔루션은 모든 프레임에서 감지와 트래킹을 실행하고, 기본적으로 1280×720 크기의 차트를 렌더링하여 출력 비디오에 바로 기록할 수 있게 합니다. 단일 인수로 "line", "bar", "pie", "area" 간에 전환할 수 있습니다.

Ultralytics YOLO를 사용한 분석
yolo solutions analytics show=True

# Pass the source
yolo solutions analytics source="path/to/video.mp4"

# Generate the pie chart
yolo solutions analytics analytics_type="pie" show=True

# Generate the bar plots
yolo solutions analytics analytics_type="bar" show=True

# Generate the area plots
yolo solutions analytics analytics_type="area" show=True

Analytics 인수#

다음은 Analytics 인수를 정리한 표입니다:

인수유형기본값설명
modelstrNoneUltralytics YOLO 모델 파일의 경로입니다.
analytics_typestr'line'그래프 유형입니다. line, bar, area 또는 pie을 지정할 수 있습니다.
figsizetuple[float, float](12.8, 7.2)Analytics 차트의 크기(인치)입니다. (12.8, 7.2)은 1280×720 프레임을 렌더링합니다.
line_widthint2Solution에서 그리는 상자, 키포인트 및 개수 표시의 선 두께입니다.
verboseboolTrue프레임별 입력 형태, 클래스 개수 및 처리 속도 로그를 활성화합니다. 추적 호출 자체는 항상 로그를 출력하지 않습니다.

Analytics 솔루션에서도 track 인수를 사용할 수 있습니다.

인수유형기본값설명
trackerstr'tracktrack.yaml'사용할 추적 알고리즘을 지정합니다. 기본 제공 옵션: botsort.yaml, bytetrack.yaml, ocsort.yaml, deepocsort.yaml, fasttrack.yaml, tracktrack.yaml.
conffloat0.25탐지에 대한 신뢰도 임계값을 설정합니다. 값을 낮추면 추적할 수 있는 객체가 늘어나지만 오탐이 포함될 수 있습니다.
ioufloat0.5중복 탐지를 필터링하기 위한 교집합 대비 합집합 (IoU) 임계값을 설정합니다.
classeslistNone클래스 인덱스로 결과를 필터링합니다. 예를 들어 classes=[0, 2, 3]은 지정된 클래스만 추적합니다.
devicestrNone추론에 사용할 장치를 지정합니다(예: cpu, cuda:0 또는 0). 사용자는 모델 실행에 사용할 CPU, 특정 GPU 또는 기타 연산 장치를 선택할 수 있습니다.
imgszint or tuple640추론 대상 이미지 크기입니다. 정사각형을 나타내는 정수 또는 (height, width) 쌍을 지정합니다. 모델 stride에 맞춰 형태가 조정됩니다.
max_detint300추적 전에 프레임별로 유지할 최대 탐지 수를 지정하여 밀집된 장면에서 솔루션이 처리하는 객체 수를 제한합니다.
quantizeint or strNone추론 정밀도: CPU 이외의 환경에서 PyTorch 및 TorchScript 모델은 16(FP16) 또는 32/unset(FP32)을 사용하며, 다른 형식은 아티팩트와 런타임이 선택하는 정밀도를 사용합니다. 더 이상 사용되지 않는 half 인수를 대체합니다.

또한 다음 시각화 인수를 지원합니다:

인수유형기본값설명
showboolFalseTrue이면 주석이 추가된 이미지나 비디오를 창에 표시합니다. 개발 또는 테스트 중 즉각적인 시각적 피드백을 얻는 데 유용합니다.

결론#

효과적인 데이터 분석을 위해서는 다양한 시각화를 언제, 어떻게 사용할지 이해하는 것이 중요합니다. 선 그래프, 막대 그래프, 원형 차트 및 영역 그래프는 데이터의 의미를 더 명확하고 효과적으로 전달하는 데 도움이 되는 기본 도구입니다. Ultralytics YOLO26 Analytics 솔루션은 객체 탐지 및 추적 결과를 바탕으로 이러한 시각화를 간편하게 생성하여 시각 데이터에서 의미 있는 인사이트를 쉽게 얻도록 지원합니다.

자주 묻는 질문#

  • Ultralytics YOLO26 Analytics로 선 그래프를 만들려면 다음 단계를 따르세요:

    1. YOLO26 모델을 불러오고 비디오 파일을 엽니다.
    2. Analytics 클래스를 analytics_type="line"로 초기화합니다.
    3. 비디오 프레임을 순회하며 각 프레임에서 솔루션을 호출해 객체 수와 같은 데이터로 선 그래프를 업데이트합니다.
    4. 차트를 저장하려면 results.plot_im을 출력 비디오에 기록합니다.

    시작점으로 위 Python 예제를 사용하세요. 전체 프레임 루프가 이미 구현되어 있으며 기본 analytics_type은 선 그래프입니다.

  • 막대 그래프 생성에 Ultralytics YOLO26을 사용하면 다음과 같은 이점이 있습니다:

    1. 실시간 데이터 시각화: 객체 탐지 결과를 막대 그래프에 통합해 동적으로 업데이트합니다.
    2. 간편한 사용: 단순한 API와 함수로 데이터를 쉽게 구현하고 시각화할 수 있습니다.
    3. 사용자 정의: 특정 요구 사항에 맞게 제목, 레이블, 색상 등을 사용자 정의할 수 있습니다.
    4. 효율성: 대량의 데이터를 효율적으로 처리하고 비디오 처리 중 플롯을 실시간으로 업데이트합니다.

    막대 그래프를 생성하려면 위 Python 예제에서 analytics_type="bar"을 설정하면 됩니다. 나머지 프레임 루프는 동일합니다. 미리 보기는 시각적 예시 섹션을 참조하세요.

  • Ultralytics YOLO26은 다음과 같은 이유로 원형 차트를 만드는 데 적합합니다:

    1. 객체 감지와의 통합: 객체 감지 결과를 원형 차트에 직접 통합하여 즉시 인사이트를 얻을 수 있습니다.
    2. 사용하기 쉬운 API: 최소한의 코드로 간단하게 설정하고 사용할 수 있습니다.
    3. 사용자 정의 가능: 색상, 레이블 등을 다양하게 사용자 정의할 수 있습니다.
    4. 실시간 업데이트: 데이터를 실시간으로 처리하고 시각화하므로 비디오 분석 프로젝트에 적합합니다.

    원형 차트를 생성하려면 위 Python 예제에서 analytics_type="pie"을 설정하세요. 자세한 내용은 가이드의 시각적 예시 섹션을 참조하세요.

  • 네. 트래킹은 Analytics 솔루션에 기본 제공됩니다. 여러 객체를 실시간으로 추적하고 30프레임마다 추적된 객체의 데이터로 차트를 새로 고치므로 선 그래프, 막대 그래프, 원형 차트, 영역 그래프에 모두 실시간 계수가 반영됩니다. 위 Python 예제의 프레임 루프가 바로 이 작업을 수행합니다. 기반 트래킹 기능에 대한 자세한 내용은 트래킹 섹션을 참조하세요.

  • Ultralytics YOLO26은 여러 가지 이유로 OpenCV 및 TensorFlow와 같은 다른 객체 탐지 솔루션과 차별화됩니다:

    1. 최첨단 정확도: YOLO26은 객체 감지, 인스턴스 분할, 시맨틱 분할 및 분류 작업에서 탁월한 정확도를 제공합니다.
    2. 간편한 사용: 사용자 친화적인 API를 통해 복잡한 코딩 없이 빠르게 구현하고 통합할 수 있습니다.
    3. 실시간 성능: 고속 추론에 최적화되어 실시간 애플리케이션에 적합합니다.
    4. 다양한 애플리케이션: 다중 객체 트래킹, 사용자 정의 모델 학습, ONNX, TensorRT, CoreML 등 다양한 형식으로의 내보내기를 지원합니다.
    5. 포괄적인 문서: 사용자가 모든 단계를 따라 할 수 있도록 풍부한 문서와 블로그 자료를 제공합니다.

댓글17

질문을 하거나 결과를 공유하거나 다른 사람을 도와주세요.

  1. User

    Hello @glenn-jocher How we can optimize/modify the code for YOLO predict, so it can also give final compiled result of prediction as graph. In case of counting objects/cells classed as different categories in images stored in a root folder. Not just the images with the prediction boxes.

    yolo train model=yolo11n.pt data=coco8.yaml epochs=100 imgsz=640

    yolo predict model=yolo11n.pt source=path/to/bus.jpg

    Like the count graph YOLO makes after training or bar/pie chart?

    Thanks

    1. User

      Hello,

      In relation to the above question, will this code work?

      #!/usr/bin/env python3 """ yolo_predict_results.py

      Run YOLO predictions on a single image or a directory of images, save annotated images, export per-image and aggregate counts to CSV, and save plots (aggregate bar chart and optional stacked per-image bar chart).

      Requirements: pip install ultralytics pandas matplotlib pillow

      Usage (recommended - command line): # Single image python yolo_predict_results.py --model /path/to/yolo11n.pt --source /path/to/bus.jpg --output results --save-annotated --plot-aggregate

      # Directory (batch)
      python yolo_predict_results.py --model /path/to/yolo11n.pt --source /path/to/images_dir --output results --save-annotated --plot-per-image --plot-aggregate

      This file includes clearly highlighted comments showing exactly where to set your model path and images directory if you prefer to hardcode them in the script instead of using CLI args. """

      import argparse from collections import Counter from pathlib import Path import sys

      import numpy as np import pandas as pd import matplotlib.pyplot as plt from PIL import Image

      try: from ultralytics import YOLO except Exception as e: print("Please install ultralytics (pip install ultralytics).") raise

      IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff", ".webp"}

      def find_images(directory: Path): return [str(p) for p in sorted(directory.rglob("*")) if p.suffix.lower() in IMAGE_EXTS]

      def predict_images(model, paths, conf=0.25, imgsz=640, device=None, save_annotated=False, out_dir=None): """ Run prediction per-image (keeps mapping simple). Returns list of dicts: {'file': path, 'counts': Counter, 'total': int} """ out_dir = Path(out_dir) if out_dir is not None else None annotated_dir = (out_dir / "annotated") if (save_annotated and out_dir is not None) else None if annotated_dir: annotated_dir.mkdir(parents=True, exist_ok=True)

      results = []
      for p in paths:
          print(f"Predicting: {p}")
          res_list = model.predict(source=p, conf=conf, imgsz=imgsz, device=device, verbose=False)
          if not res_list:
              print(f"Warning: no result for {p}")
              continue
          r = res_list[0]
      
          counts = Counter()
          try:
              box_cls = getattr(r.boxes, "cls", None)
              if box_cls is not None:
                  try:
                      arr = box_cls.cpu().numpy()
                  except Exception:
                      arr = np.array(box_cls)
                  arr = arr.astype(int).flatten()
                  for c in arr:
                      name = model.names.get(int(c), str(int(c)))
                      counts[name] += 1
          except Exception as e:
              print(f"Warning: could not parse classes for {p}: {e}")
      
          total = sum(counts.values())
          results.append({"file": p, "counts": counts, "total": total})
      
          if save_annotated and annotated_dir:
              try:
                  ann = r.plot()
                  if isinstance(ann, np.ndarray):
                      img_out = Image.fromarray(ann)
                  else:
                      img_out = ann
                  out_path = annotated_dir / (Path(p).stem + "_annotated" + Path(p).suffix)
                  img_out.save(out_path)
              except Exception as e:
                  print(f"Warning: failed to save annotated image for {p}: {e}")
      
      return results

      def build_dataframe(summary): all_classes = set() for row in summary: all_classes.update(row["counts"].keys()) classes = sorted(all_classes)

      rows = []
      for row in summary:
          data = {cls: row["counts"].get(cls, 0) for cls in classes}
          data["file"] = row["file"]
          data["total"] = row["total"]
          rows.append(data)
      
      if not rows:
          # Return empty dataframe
          df = pd.DataFrame(columns=["file", "total"] + classes)
      else:
          df = pd.DataFrame(rows)
          cols = ["file"] + classes + ["total"]
          df = df[cols]
      return df, classes

      def save_csvs(summary, out_dir: Path): df, classes = build_dataframe(summary) out_dir.mkdir(parents=True, exist_ok=True) csv1 = out_dir / "counts_per_image.csv" df.to_csv(csv1, index=False) print(f"Saved per-image counts to: {csv1}")

      agg = Counter()
      for r in summary:
          agg.update(r["counts"])
      agg_series = pd.Series(dict(agg)).sort_values(ascending=False)
      csv2 = out_dir / "aggregate_counts.csv"
      agg_series.to_csv(csv2, header=["count"])
      print(f"Saved aggregate counts to: {csv2}")
      return df, classes, agg

      def plot_aggregate(agg_counter, out_path: Path): names = list(agg_counter.keys()) counts = [agg_counter[n] for n in names] fig, ax = plt.subplots(figsize=(max(6, len(names) * 0.6), 5)) ax.bar(names, counts, color="tab:blue") ax.set_ylabel("Count") ax.set_title("Aggregate object counts") plt.xticks(rotation=45, ha="right") plt.tight_layout() out_path.parent.mkdir(parents=True, exist_ok=True) fig.savefig(out_path) plt.close(fig) print(f"Saved aggregate plot to: {out_path}")

      def plot_stacked_per_image(df: pd.DataFrame, classes, out_path: Path, top_n=50): if df.empty: print("No per-image data to plot.") return plot_df = df.copy() if top_n and len(plot_df) > top_n: plot_df = plot_df.sort_values("total", ascending=False).head(top_n) x = plot_df["file"].apply(lambda p: Path(p).name).tolist() bottoms = np.zeros(len(plot_df)) fig, ax = plt.subplots(figsize=(max(8, len(x) * 0.6), 6)) for cls in classes: vals = plot_df[cls].values ax.bar(x, vals, bottom=bottoms, label=cls) bottoms += vals ax.set_ylabel("Counts") ax.set_title("Per-image stacked counts") ax.legend(bbox_to_anchor=(1.05, 1), loc="upper left") plt.xticks(rotation=45, ha="right") plt.tight_layout() out_path.parent.mkdir(parents=True, exist_ok=True) fig.savefig(out_path) plt.close(fig) print(f"Saved per-image stacked plot to: {out_path}")

      def main(): ap = argparse.ArgumentParser(description="YOLO predict -> save CSV + plots") ap.add_argument("--model", required=False, help="Path to YOLO model (.pt) (e.g., yolo11n.pt)") ap.add_argument("--source", required=False, help="Image file or directory of images") ap.add_argument("--output", required=False, help="Output directory", default="results") ap.add_argument("--conf", type=float, default=0.25, help="Confidence threshold") ap.add_argument("--imgsz", type=int, default=640, help="Image size for inference") ap.add_argument("--device", type=str, default=None, help="Device (e.g., 0 or 'cpu')") ap.add_argument("--save-annotated", action="store_true", help="Save annotated images") ap.add_argument("--plot-per-image", action="store_true", help="Save stacked per-image plot") ap.add_argument("--plot-aggregate", action="store_true", help="Save aggregate bar chart") ap.add_argument("--top-n", type=int, default=50, help="Top N images for per-image plot when many images")

      # Parse CLI args (recommended usage)
      args = ap.parse_args()
      
      # -------------------------------------------------------------------------
      # HIGHLIGHT 1: If you want to hardcode paths, replace the `args = ap.parse_args()` line
      # with the block below. Edit the two highlighted lines inside the block:
      #    model="..."   <-- SET YOUR MODEL FILE PATH HERE
      #    source="..."  <-- SET YOUR IMAGE FILE OR IMAGES DIRECTORY PATH HERE
      #
      # Example (UNCOMMENT and EDIT, then COMMENT OUT or REMOVE the args = ap.parse_args() above):
      #
      # args = argparse.Namespace(
      #     model="/path/to/yolo11n.pt",       # <<< HIGHLIGHT: set model path here (absolute or relative)
      #     source="/path/to/images_or_image", # <<< HIGHLIGHT: set image file or images directory path here
      #     output="results",
      #     conf=0.25,
      #     imgsz=640,
      #     device=None,
      #     save_annotated=True,
      #     plot_per_image=True,
      #     plot_aggregate=True,
      #     top_n=50
      # )
      # -------------------------------------------------------------------------
      
      # -------------------------------------------------------------------------
      # HIGHLIGHT 2: If you prefer using the command-line, supply these two args when
      # running the script:
      #   --model /path/to/yolo11n.pt
      #   --source /path/to/images_or_image
      # These correspond to the variables used below: args.model and args.source
      # -------------------------------------------------------------------------
      
      if not args.model or not args.source:
          print("Error: --model and --source are required (or hardcode them in the script).")
          print("Example:")
          print("  python yolo_predict_results.py --model /path/to/yolo11n.pt --source /path/to/images --output results --save-annotated --plot-aggregate")
          sys.exit(1)
      
      model_path = Path(args.model)
      source = Path(args.source)
      out_dir = Path(args.output)
      out_dir.mkdir(parents=True, exist_ok=True)
      
      print(f"Loading model: {model_path}")
      model = YOLO(str(model_path))
      
      if source.is_dir():
          files = find_images(source)
          if not files:
              print(f"No images found under {source}")
              sys.exit(1)
      elif source.is_file():
          files = [str(source)]
      else:
          print(f"Source path not found: {source}")
          sys.exit(1)
      
      summary = predict_images(
          model=model,
          paths=files,
          conf=args.conf,
          imgsz=args.imgsz,
          device=args.device,
          save_annotated=args.save_annotated,
          out_dir=out_dir,
      )
      
      if not summary:
          print("No predictions were produced.")
          sys.exit(0)
      
      df, classes, agg = save_csvs(summary, out_dir)
      
      if args.plot_aggregate:
          plot_aggregate(agg, out_dir / "aggregate_counts.png")
      
      if args.plot_per_image:
          plot_stacked_per_image(df, classes, out_dir / "per_image_stacked_counts.png", top_n=args.top_n)
      
      print("All done. Results in:", out_dir.resolve())

      if name == "main": main()

      @glenn-jocher @pderrenger

    2. Glenn JocherUltralytics

      @MUK003 great question, and thanks for sharing the script in detail.

      The short answer is: yes, this is a reasonable way to get per-image and aggregate count graphs from YOLO11 predictions, since YOLO('yolo11n.pt') returns Results objects where r.boxes.cls holds the class indices and your Counter/CSV/Matplotlib logic will work on top of that. I’d recommend first running it on a very small image folder and confirming that the numbers in counts_per_image.csv and aggregate_counts.csv match what you expect from a few sample images.

      From the Ultralytics side there’s currently no built-in yolo predict CLI flag that directly produces those bar/pie charts like training; your Python approach (or, for video streams, the solutions.Analytics charts) is the right pattern. For reference on how analytics is structured inside Ultralytics, you can also glance at the Analytics solution API docs.

    1. Glenn JocherUltralytics(수정됨)

      @yeongnamtan to integrate the line graph with a line counter, use the Analytics class to update the line graph with the total object counts per frame. Ensure you initialize the Analytics with analytics_type="line" and update it within your video processing loop. For detailed guidance, please refer to the analytics section in the documentation.

    1. Glenn JocherUltralytics

      @Peymankar hello!

      To count the number of left or right turns at an intersection using Ultralytics YOLO, you can set up a tracking system that identifies and follows each vehicle's trajectory. Here’s a brief outline on how you might approach this:

      1. Track Vehicles: Use the YOLO model to detect and track vehicles. You can use the model.track() function to keep track of each vehicle's movement frame by frame.

      2. Define Zones: Define areas or lines within the video frame that represent the boundaries of different turn directions (left, right).

      3. Analyze Trajectories: Analyze the paths of tracked vehicles to determine when they cross these defined zones. This can be done by checking the intersection of vehicle tracks with these zones and classifying the movement as a left or right turn based on the zone they intersect.

      4. Count Turns: Maintain a count of how many vehicles make left or right turns based on these intersections.

      For a more detailed guide on setting up vehicle tracking and analyzing trajectories, you might find the tracking and analytics features in the Ultralytics documentation helpful. Implementing this will require some custom coding to define zones and analyze paths relative to these zones.

      If you need further assistance or more specific guidance, feel free to ask. Happy coding! 😊

  2. yeongnamtanGitHub

    ani = FuncAnimation(fig, animate, frames=range(int(cap.get(cv2.CAP_PROP_FRAME_COUNT))), blit=False, interval=1000/fps, repeat=False)

    plt.show()

    The code is still not working... I

    error meesage ... WARNING ⚠️ best.pt appears to require 'dill', which is not in ultralytics requirements. AutoInstall will run now for 'dill' but this feature will be removed in the future. Recommend fixes are to train a new model using the latest 'ultralytics' package or to run a command with an official YOLOv8 model, i.e. 'yolo predict model=yolov8n.pt' requirements: Ultralytics requirement ['dill'] not found, attempting AutoUpdate... Collecting dill Downloading dill-0.3.8-py3-none-any.whl (116 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 116.3/116.3 kB 4.9 MB/s eta 0:00:00 Installing collected packages: dill Successfully installed dill-0.3.8

    requirements: AutoUpdate success ✅ 5.8s, installed 1 package: ['dill'] requirements: ⚠️ Restart runtime or rerun command for updates to take effect

    requirements: Ultralytics requirement ['lapx>=0.5.2'] not found, attempting AutoUpdate... Collecting lapx>=0.5.2 Downloading lapx-0.5.9-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.7 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.7/1.7 MB 11.8 MB/s eta 0:00:00 Requirement already satisfied: numpy>=1.21.6 in /usr/local/lib/python3.10/dist-packages (from lapx>=0.5.2) (1.25.2) Installing collected packages: lapx Successfully installed lapx-0.5.9

    requirements: AutoUpdate success ✅ 7.4s, installed 1 package: ['lapx>=0.5.2'] requirements: ⚠️ Restart runtime or rerun command for updates to take effect

    0: 384x640 2 fishs, 134.7ms Speed: 13.4ms preprocess, 134.7ms inference, 747.7ms postprocess per image at shape (1, 3, 384, 640)

    DisabledFunctionError Traceback (most recent call last) in <cell line: 26>() 37 clswise_count[model.names[int(cls)]] = 1 38 ---> 39 analytics.update_bar(clswise_count) 40 cv2_imshow('Bar Plot', frame) 41 clswise_count = {}

    1 frames /usr/local/lib/python3.10/dist-packages/google/colab/_import_hooks/_cv2.py in wrapped(*args, **kwargs) 46 def wrapped(*args, **kwargs): 47 if not os.environ.get(env_var, False): ---> 48 raise DisabledFunctionError(message, name or func.name) 49 return func(*args, **kwargs) 50

    DisabledFunctionError: cv2.imshow() is disabled in Colab, because it causes Jupyter sessions to crash; see https://github.com/jupyter/notebook/issues/3935. As a substitution, consider using from google.colab.patches import cv2_imshow

    1. Paula DerrengerUltralytics

      Hello,

      Thank you for sharing the details of the issue you're encountering. It seems like the dill and lapx packages were missing but have now been successfully installed. Please ensure you restart your runtime or rerun your command to allow the updates to take effect, as suggested by the AutoUpdate messages.

      Regarding the DisabledFunctionError for cv2.imshow() in Colab, this function is indeed disabled because it can cause Jupyter sessions to crash. As an alternative, you can use cv2_imshow from the google.colab.patches module to display images in Colab notebooks. Here’s how you can modify your code:

      from google.colab.patches import cv2_imshow
      
      # Replace cv2.imshow with cv2_imshow
      cv2_imshow(frame)

      This should allow you to display images without causing any issues in your Colab environment.

      If you have any more questions or need further assistance, feel free to ask. Happy coding! 🚀

    1. Paula DerrengerUltralytics

      @yeongnamtan hello,

      It seems like you're encountering an issue with cv2.imshow not being present in the bar plot code example. This function is indeed necessary to display the frames with the visualizations in real-time. To resolve the error, you can add the following line just after updating the bar plot in the loop:

      cv2.imshow('Bar Plot', frame)

      Make sure to include this inside the loop where frames are being processed, and it will display the updated frame with the bar plot. Additionally, ensure that you have the line if cv2.waitKey(1) & 0xFF == ord('q'): to handle the window closure properly.

      If you need further assistance or have more questions, feel free to ask!

  3. yeongnamtanGitHub

    I tried to use google colab but it is giving me error because of cv2.imshow... How can I modify it to use cv2_imshow instead ... from google.colab.patches import cv2_imshow # Import cv2_imshow from google.colab.patches

    DisabledFunctionError: cv2.imshow() is disabled in Colab, because it causes Jupyter sessions to crash; see https://github.com/jupyter/notebook/issues/3935. As a substitution, consider using from google.colab.patches import cv2_imshow

    1. Paula DerrengerUltralytics

      Hello! To use cv2_imshow instead of cv2.imshow in Google Colab, you can make a simple modification to your code. First, ensure you import cv2_imshow from google.colab.patches as you've mentioned. Then, replace all instances of cv2.imshow with cv2_imshow. Here’s how you can do it:

      1. Import the function:

        from google.colab.patches import cv2_imshow
      2. Replace cv2.imshow with cv2_imshow:

        # Instead of cv2.imshow("Frame", frame)
        cv2_imshow(frame)

      This change should resolve the issue with displaying images in Google Colab. Let me know if there's anything else you need help with! 😊