YOLO11如何RGB三通道转换为灰色单通道
1. ./ultralytics/cfg/models/v8/yolov8.yaml(也可是你自己修改的yaml文件)文件加 ch:1.
nc: 1 # number of classes
ch: 1
2. 修改 ultralytics/utils/checks.py 文件 (“-”表示删除;“+”表示添加 ;建议保留原代码注释后续方便改回。)
ctrl+f 搜索 ConnectionError
try:
from ultralytics import YOLO
- assert amp_allclose(YOLO("yolov8n.pt"), im)
+ # assert amp_allclose(YOLO("yolo11n.pt"), im)
LOGGER.info(f"{prefix}checks passed ✅")
except ConnectionError:
LOGGER.warning(
f"{prefix}checks skipped ⚠️. Offline and unable to download YOLO11n for AMP checks. {warning_msg}"
)
3. 修改 ultralytics/nn/tasks.py文件 class BaseModel 的 损失函数def loss
def loss(self, batch, preds=None):
"""
Compute loss.
Args:
batch (dict): Batch to compute loss on
preds (torch.Tensor | List[torch.Tensor]): Predictions.
"""
if getattr(self, "criterion", None) is None:
self.criterion = self.init_criterion()
+ batch['img'] = batch['img'][:,:1,:,:] # ch 3 to 1
preds = self.forward(batch["img"]) if preds is None else preds
return self.criterion(preds, batch)
4. 修改 /ultralytics/nn/autobackend.py文件
ctrl+f 搜索 warmup
def warmup(self, imgsz=(1, 3, 640, 640)): -----> def warmup(self, imgsz=(1, 1, 640, 640)):
5. 修改 /ultralytics/engine/validator.py文件 ctrl+f 搜索 warmup
model.warmup(imgsz=(1 if pt else self.args.batch, 3, imgsz, imgsz))
------> model.warmup(imgsz=(1 if pt else self.args.batch, 1, imgsz, imgsz))
ctrl+f 搜索 dt[1]
with dt[1]:
+ batch["img"] = batch["img"][:,:1,:,:]
preds = model(batch["img"], augment=augment)
6.修改 /ultralytics/engine/predictor.py文件
ctrl+f 搜索 warmup
if not self.done_warmup:
- self.model.warmup(imgsz=(1 if self.model.pt or self.model.triton else self.dataset.bs, 3, *self.imgsz))
+ self.model.warmup(imgsz=(1 if self.model.pt or self.model.triton else self.dataset.bs, 1, *self.imgsz))
+ # self.model.warmup(imgsz=(1 if self.model.pt or self.model.triton else the dataset.bs, 3, *self.imgsz))
self.done_warmup = True
7.修改ultralytics/models/yolo/detect/val.py文件
ctrl+f 搜索 preprocess
def preprocess(self, batch):
"""Preprocesses batch of images for YOLO training."""
batch["img"] = batch["img"].to(self.device, non_blocking=True)
batch["img"] = (batch["img"].half() if self.args.half else batch["img"].float()) / 255
+ batch['img'] = batch['img'][:, :1, :, :]
for k in ["batch_idx", "cls", "bboxes"]:
batch[k] = batch[k].to(self.device)
8.修改ultralytics/engine/predictor.py
ctrl+f 搜索 ascontiguousarray
not_tensor = not isinstance(im, torch.Tensor)
if not_tensor:
im = np.stack(self.pre_transform(im))
im = im[..., ::-1].transpose((0, 3, 1, 2)) # BGR to RGB, BHWC to BCHW, (n, 3, h, w)
+ im = im[:, :1, :, :]
im = np.ascontiguousarray(im) # contiguous
im = torch.from_numpy(im)
YOLO11如何RGB三通道转换为灰色单通道
http://localhost:8090//archives/yolo11ru-he-san-tong-dao-rgbzhuan-huan-wei-hui-se-dan-tong-dao