Dice 99%, still a centimetre off: scrotal circumference from 3D images

[This article was first published on Data Science Guts, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

In 2022 I was one of four authors of a paper on measuring the scrotal circumference of young bulls without touching them (Bremer, Maj, Nordbø and Kommisrud, Smart Agricultural Technology). Scrotal circumference – SC – is an important measurement in selecting bulls for a breeding programme. The usual method requires the animal to be restrained, because the scrotum is measured by hand with a tape. The idea was to take a 3D picture instead.

A “3D picture” here is not a photograph. A depth camera records, for every pixel, how far away the thing in that pixel is – in millimetres, not in colour. The one we used, an Intel RealSense D415, does it the way two eyes do: two cameras a few centimetres apart see the scene from slightly different angles, and the shift of each point between the two views gives its distance. Shown on screen, a depth image is a grey picture in which the shade is the distance.

That distance is what makes a measurement possible. In an ordinary photograph an object 10 cm across can be any number of pixels wide, depending on how far the camera was; with the distance known for every pixel, a width in pixels becomes a width in millimetres. So the plan was: find the scrotum in the depth image with a neural network, fit an ellipse to its outline, turn the ellipse’s size into centimetres with the camera’s distance, and read off a circumference.

I wrote the network, and it was very good at its job. On held-out images it found the scrotum with a Dice coefficient of 99.3%. The paper’s recommendation was to use the method on bulls from about six months on, and only on images that show the scrotum as a full circle. There the circumference came out on average about a centimetre larger than the tape – 2.0 cm at six months, 1.1 at nine and 0.6 at twelve.

A Dice of 99.3% says the masks are nearly perfect. So is that centimetre in the 0.7% – or somewhere the Dice was never asked to look? The data is still on my disk, and the question has a direct test: replace the network’s masks with the ones a person drew by hand, keep everything else, and see whether the error goes away.

The pipeline

Every step of it, as the paper describes it:

flowchart LR
  A["3D image<br/>(depth per pixel)"] --> B["U-Net<br/>mask of the scrotum"]
  B --> C["keep the largest<br/>object"]
  C --> D["convex hull,<br/>ellipse fit"]
  D --> E["pixels to mm<br/>(field of view,<br/>median depth)"]
  E --> F["ellipse perimeter<br/>= SC"]
  F -.- T["compared with<br/>the tape measure"]

The third box is easy to miss and is there for a reason. Most predicted masks were one solid object, as they should be, but some carried a second, small blob somewhere else in the image (the paper’s Fig. 3 shows one at the edge of the frame). An ellipse fitted to two objects describes neither, so connected-component labelling counts the objects in the mask and only the largest one is kept.

The data

Norwegian Red bull calves at a performance testing station, measured four times: on arrival in quarantine at 3-5 months (group Q), then at about 6, 9 and 12 months. At every visit veterinarians measured SC with a scrotal tape, and the scrotum was photographed from below with an Intel RealSense D415 depth camera – one image per bull per visit. Each image was also rated for quality: 2 for a full circle, 1 for a partial one, 0 for not enough to see.

The paper could not share the data, so neither can this post: the code below runs on my copy of it, and only aggregates leave it.

import json
import numpy as np
import pandas as pd
from PIL import Image, ImageDraw

visits = pd.read_csv(DATA / "results.csv")        # one row per 3D image
quality = pd.read_csv(DATA / "circle_info.csv")   # 0, 1 or 2, rated by eye
visits = visits.merge(quality, on="filename")
visits["key"] = visits.filename.str.extract(r"([^/]+)\.png$", expand=False)
visits = visits.rename(columns={"SC": "tape", "prediction": "network",
                                "circle": "quality"})
visits.columns.tolist()
['id', 'group', 'tape', 'filename', 'network', 'quality', 'key']

tape is the veterinarian’s measurement and network the circumference the 2022 pipeline computed from the network’s mask, rounded to a whole centimetre as it was then. The paper’s analysis left out 54 of the 424 images – repeat captures of five bulls and images rejected on inspection – and so does this one:

visits = visits[~visits.key.isin(excluded)]
visits.groupby("group", sort=False).agg(
    images=("tape", "size"), tape=("tape", "mean")).round(1)
images tape
group
Q 57 15.4
6 88 21.6
9 124 29.1
12 101 34.0

And the images by quality:

order = ["Q", "6", "9", "12"]
pd.crosstab(visits.group, visits.quality).loc[order]
quality 0 1 2
group
Q 14 30 13
6 14 31 43
9 7 33 84
12 8 18 75

The youngest bulls are the hard case for the camera. At three to five months the scrotum is small and not well pronounced, and only 13 of the 57 quarantine images show it as a full circle. That is why the paper recommended bulls from six months on and quality-2 images only, and why the numbers below are for those images first.

From a mask to centimetres

Each image comes with its depth map – the distance from the camera to every pixel, in millimetres – read by a helper depth_map(key). Two more read the outline drawn around the scrotum in labelme, 30 to 40 points per image, and the network’s mask:

def hand_mask(key):
    """The scrotum outline drawn in labelme, as a boolean mask."""
    shape = json.loads((DATA / "img" / f"{key}.json").read_text())
    points = [tuple(p) for p in shape["shapes"][0]["points"]]
    canvas = Image.new("L", (640, 480), 0)
    ImageDraw.Draw(canvas).polygon(points, fill=1)
    return np.array(canvas, dtype=bool)


def network_mask(key):
    """The mask predicted by the network retrained further down."""
    return np.array(Image.open(RUN / "pred" / f"{key}.png")) > 0

One image through all of it: the 3D image as the network sees it, the depth in millimetres, the outline drawn by hand, and the network’s prediction – this one from a held-out image on which the network also found a second, small object:

import matplotlib.pyplot as plt
from scipy import ndimage

ink = "#888888"
split = pd.read_csv(RUN / "split.csv")
held_out = split.key[split.split == "test"]
key = next(k for k in sorted(held_out)
           if ndimage.label(network_mask(k))[1] == 2)
depth = depth_map(key)
image = np.array(Image.open(DATA / "img" / f"{key}.png"))[..., 0]
viridis = plt.get_cmap("viridis").with_extremes(bad="#cfcfcf")
panels = [("3D image", image, "gray"),
          ("depth (mm)", depth, viridis),
          ("hand mask", hand_mask(key), "gray"),
          ("network mask", network_mask(key), "gray")]
fig, axes = plt.subplots(1, 4, figsize=(10, 2.4))
for ax, (title, im, cmap) in zip(axes, panels):
    ax.imshow(im, cmap=cmap)
    ax.set_title(title, color=ink, fontsize=10)
    ax.axis("off")
fig.patch.set_alpha(0)

One held-out image: the 3D image as saved (left), its depth in mm (grey is no depth), the hand-drawn mask, and the network’s mask before only the largest object is kept.

Then the measurement itself, as the paper describes it: take the outline’s convex hull, fit an ellipse to it by direct least squares, turn its two semi-axes from pixels into angles with the camera’s field of view (66.5 by 40.5 degrees over 640 by 480 pixels), and into millimetres with the median distance to the scrotum. The perimeter of that ellipse, by a Padé approximation, is the circumference.

The code of this step is not shown: the measurement belongs to the original project, and this post is about the segmentation in front of it. Below it is one function, circumference(mask, depth), which takes a mask and a depth map and returns centimetres:

visits["hand"] = [circumference(hand_mask(k), depth_map(k))
                  for k in visits.key]
visits[["tape", "network", "hand"]].describe().round(1)
tape network hand
count 370.0 370.0 370.0
mean 26.5 28.6 29.1
std 6.9 6.4 6.2
min 12.0 7.0 13.6
25% 21.0 24.0 24.3
50% 28.0 30.0 30.4
75% 32.0 34.0 34.0
max 40.0 41.0 41.5

What that looks like on two full-circle images, one at six months and one at twelve, each the image closest to its group’s median error.

The depth map from below (darker is closer, grey is no depth), the hand-drawn outline (white) and the ellipse fitted to its hull (orange), for a bull at 6 months and one at 12 months.

Two things are worth seeing here before any numbers. The scrotum is ringed by grey, pixels where the camera returned no depth because the surface turns away from it – the edge the whole measurement depends on is exactly where the depth is missing. And the ellipse is not the outline: it is fitted to the outline’s convex hull, which bridges every dent in it – such as a notch between the testes – and is never smaller than the outline itself.

Hand-drawn masks, same error

The paper reported the mean prediction error – the mean of tape minus prediction, so a negative number is an image that measures too large – and its mean square, per age group and image quality. The same two for the full-circle images, for the network’s masks and for the hand-drawn ones:

def errors(v, col):
    e = v.tape - v[col]
    return pd.Series({"images": len(e), "MPE": e.mean(),
                      "MSPE": (e ** 2).mean()})


good = visits[visits.quality == 2]
table = pd.concat({col: good.groupby("group").apply(errors, col)
                   for col in ["network", "hand"]}, axis=1).loc[order]
table.round(2)
network hand
images MPE MSPE images MPE MSPE
group
Q 13.0 -2.46 8.31 13.0 -2.81 9.75
6 43.0 -1.98 6.80 43.0 -2.02 7.03
9 84.0 -1.11 4.58 84.0 -1.49 4.94
12 75.0 -0.61 5.21 75.0 -1.07 6.48

The network columns are the quality-2 rows of the paper’s Table 4 to the second decimal (and over all 370 images, its Table 3), which says this is the same data and the same images. The hand columns are the answer to the question: with a person’s outline in place of the network’s, the error does not go away. It grows a little – by 0.04 cm at six months, 0.3-0.5 cm in the other groups. The partial images tell the same story at two to four centimetres; the hand masks do no better there either.

That is less strange than it sounds. A hand-drawn outline is not the truth either; it is one careful person’s idea of where the edge is, and the network learnt that idea from 60% of these very outlines. The two agree closely:

good[["tape", "network", "hand"]].corr().round(3)
tape network hand
tape 1.000 0.942 0.945
network 0.942 1.000 0.988
hand 0.945 0.988 1.000

0.988 between network and hand, against 0.94 between either of them and the tape. The masks are not where the two methods part company with the veterinarian. The centimetre lives between the mask and the tape – in the geometry that turns an outline seen from below into a circumference measured around – and a Dice coefficient, which compares a mask with a mask, cannot see it at all.

Bland and Altman

When two methods measure the same thing, the standard picture is Bland and Altman’s: for every image, the difference between the methods against their mean. A constant bias is a horizontal band; a bias that depends on size is a slope.

diff = good.tape - good.hand
mean = (good.tape + good.hand) / 2
fig, ax = plt.subplots(figsize=(7, 4))
for g in order:
    s = good.group == g
    ax.scatter(mean[s], diff[s], s=14, alpha=0.7, label=g)
for y, ls in [(diff.mean(), "-"), (diff.mean() + 1.96 * diff.std(), "--"),
              (diff.mean() - 1.96 * diff.std(), "--")]:
    ax.axhline(y, color=ink, linestyle=ls, linewidth=1)
ax.set_xlabel("mean of tape and image (cm)", color=ink)
ax.set_ylabel("tape - image (cm)", color=ink)
ax.tick_params(colors=ink)
for s in ax.spines.values():
    s.set_color(ink)
legend = ax.legend(title="age group", frameon=False, labelcolor=ink)
legend.get_title().set_color(ink)
fig.patch.set_alpha(0)
ax.set_facecolor("none")

Tape minus the image measurement from hand-drawn masks, against their mean, for the 215 full-circle images. The solid line is the mean difference, the dashed lines the 95% limits of agreement.
slope, intercept = np.polyfit(mean, diff, 1)
{"bias": round(float(diff.mean()), 2),
 "limits": round(float(1.96 * diff.std()), 2),
 "slope": round(float(slope), 3)}
{'bias': -1.53, 'limits': 3.85, 'slope': 0.088}

On average the image measures 1.5 cm more than the tape, and the limits of agreement are 3.9 cm either side of that: a single image can come out anywhere from about 2 cm too small to 5 cm too large. Part of that band belongs to the tape, not the camera – the paper found repeat tape measurements to agree within a centimetre, on bulls that move and can pull the scrotum up towards the body – but the band, more than the mean, is what a single image is worth.

And the band is tilted. The slope of 0.088 means that for every 10 cm of scrotum the difference moves by almost a centimetre towards zero: the smaller the animal, the more the image overstates it. That is the age effect in the paper’s Table 3 seen without the age groups. Age and size travel together here, so this picture cannot say which of the two it is; but any fixed error in the geometry – a millimetre or two of hull outside the true edge, a distance read off the front of the scrotum rather than its middle – would behave exactly like this, because it is a larger share of a small circumference.

The paper’s open question: a straight line on top

The paper ended on a hypothesis it did not test: a simple linear model fitted on top of the measurement “could potentially decrease prediction [error] even more. This hypothesis, however, has to be confirmed.” The slope above is the reason it might. Testing it honestly means fitting the line on some bulls and scoring it on others – never the same bull on both sides, because four visits of one animal are not four independent images. Again on the full-circle images:

rng = np.random.default_rng(1)
bulls = good.id.unique()
fold = dict(zip(bulls, rng.permutation(len(bulls)) % 5))
good = good.assign(fold=good.id.map(fold))

for col in ["network", "hand"]:
    good[f"{col}_line"] = np.nan
    for k in range(5):
        train, test = good.fold != k, good.fold == k
        fit = good[train]
        b, a = np.polyfit(fit[col], fit.tape, 1)
        good.loc[test, f"{col}_line"] = a + b * good.loc[test, col]

lines = {col: good.groupby("group").apply(errors, col)
         for col in ["network_line", "hand_line"]}
pd.concat(lines, axis=1).loc[order].round(2)
network_line hand_line
images MPE MSPE images MPE MSPE
group
Q 13.0 -0.92 3.23 13.0 -0.99 3.03
6 43.0 -0.60 3.39 43.0 -0.31 3.17
9 84.0 0.07 3.50 84.0 0.03 2.76
12 75.0 0.40 5.24 75.0 0.30 5.68

It works where there was a bias to remove. The line takes the mean error to within 0.6 cm at six months and to almost zero at nine, and halves the mean squared error at six months – from 6.8 to 3.4 cm² for the network’s masks, and from 7.0 to 3.2 for the hand-drawn ones. At twelve months, where the method was already within 0.6 cm, it changes little. (The 13 full-circle images of the youngest bulls improve the most, but 13 images are too few to lean on.) The paper’s hypothesis holds, on bulls the line never saw.

One straight line, two numbers, fixed much of what the Dice of 99.3% could not. Not because the network got better, but because the error was never in the network.

The network, five years later

The paper says its network was “build, trained and validated using ‘pyplatypus’” – the 2020 package, which no longer runs. The same network in today’s rplatypus or pyplatypus is one specification: a U-Net on 256 by 512 single-channel images, five blocks, focal loss, Adam, trained on the hand-drawn masks. One thing is different from 2022: the 60/20/20 split is by bull, so the four visits of one animal never sit on both sides of it.

library(rplatypus)

spec <- platypus_spec(
  data = segmentation_data(
    "cases.csv", mode = "config_file",   # key, 3D image, hand mask
    colormap = binary_colormap,
    split = list(fractions = c(0.6, 0.2, 0.2),
                 group_by = "^(\\d+)_", seed = 1)   # by bull
  ),
  models = list(
    u_net("scrotum", input_shape = c(256, 512), channels = 1,
          blocks = 5, filters = 16, batch_size = 8, epochs = 100,
          loss = loss_focal(),
          metrics = list(metric_dice(include_background = FALSE)),
          optimizer = optimizer_adam(1e-3),
          callbacks = list(callback_early_stopping(
            monitor = "val_dice", patience = 10)))
  ),
  seed = 1
)
fit <- platypus_fit(spec)
evaluate(fit, split = "test")
masks <- predict(fit, split = "test", space = "source")
import pyplatypus as pp

engine = pp.build_engine(pp.from_dict({
    "task": "semantic_segmentation",
    "data": {
        "train_path": "cases.csv",          # key, 3D image, hand mask
        "mode": "config_file",
        "colormap": [[0, 0, 0], [255, 255, 255]],
        "split": {"fractions": [0.6, 0.2, 0.2],
                  "group_by": r"^(\d+)_", "seed": 1},   # by bull
    },
    "models": [{
        "name": "scrotum", "architecture": "u_net",
        "input_shape": [256, 512], "channels": 1,
        "blocks": 5, "filters": 16, "batch_size": 8, "epochs": 100,
        "loss": {"name": "focal"},
        "metrics": [{"name": "dice", "include_background": False}],
        "optimizer": {"name": "adam", "learning_rate": 0.001},
        "callbacks": [{"name": "early_stopping", "monitor": "val_dice",
                       "patience": 10, "restore_best": True}],
    }],
    "seed": 1,
}))
engine.fit()
engine.evaluate("test")
masks = engine.predict_stream("scrotum", split="test", space="source")

On a GPU it stopped after 37 epochs of about seven seconds each, with the best at epoch 27, and scored a Dice of 0.962 on the 87 held-out images. Not 99.3%. The difference is not the network; it is which pixels the Dice counts:

def dice(a, b):
    return 2 * (a & b).sum() / (a.sum() + b.sum())


def dice_with_background(a, b):
    """Both classes stacked, every pixel counted: background included."""
    return dice(np.stack([~a, a]), np.stack([~b, b]))


pairs = [(network_mask(k), hand_mask(k)) for k in held_out]
scores = pd.DataFrame(
    [(dice(n, h), dice_with_background(n, h)) for n, h in pairs],
    columns=["scrotum only", "with background"])
scores.mean().round(4)
scrotum only       0.9624
with background    0.9986
dtype: float64

The scrotum covers about 2% of the image. A Dice that counts the background as a second class is mostly a score for agreeing that the floor is not a scrotum, and it reads 0.999 for masks whose scrotum-only Dice is 0.96. That is my reading of the 99.3% in the paper: the metric I used then counted both classes. It does not make the masks bad - 0.96 is a good mask - but it is a number about the background, and it was the number in the abstract’s neighbourhood.

The second object is real too:

objects = [ndimage.label(network_mask(k))[1] for k in held_out]
pd.Series(objects, name="objects").value_counts()
objects
1    81
2     3
3     2
5     1
Name: count, dtype: int64
def keep_largest(mask):
    """Connected-component labelling: only the largest object stays."""
    labels, n = ndimage.label(mask)
    if n <= 1:
        return mask
    sizes = ndimage.sum(mask, labels, range(1, n + 1))
    return labels == np.argmax(sizes) + 1


test = good[good.key.isin(held_out)].copy()
test["pyplatypus"] = [
    circumference(keep_largest(network_mask(k)), depth_map(k))
    for k in test.key]
pd.DataFrame({col: errors(test, col)
              for col in ["network", "hand", "pyplatypus"]}).round(2)
network hand pyplatypus
images 47.00 47.00 47.00
MPE -1.14 -1.23 -1.09
MSPE 5.84 6.60 5.48

Three masks on the same 47 held-out full-circle images, and one answer: the 2022 network, the hand-drawn outline and the retrained one all measure 1.1-1.2 cm too large, with mean squared errors between 5.5 and 6.6 cm². (The 2022 network was trained on a split by image rather than by bull, so some of these images were in its training set - and it is no better for it.) A better network has little left to win here: the error sits after the mask.

What to take from this

A Dice coefficient compares a mask with a mask. It is the right number for the network, and it says nothing about the measurement the mask is for. Here it was 99.3% - partly because it counted the background, which is worth checking in any Dice you read - and the circumference was still about a centimetre off on the best images, and more on young bulls and partial images; replacing the network with a person’s outline did not make that any smaller.

When a pipeline turns a segmentation into a physical number, score it on the physical number, against the reference it will be compared with, and split the error by size before splitting it by anything else. And test the cheap fix before the expensive one: a straight line fitted on other animals did more for this measurement than any amount of extra Dice could have.

Acknowledgements

Thanks to my co-authors of the 2022 paper - Joanna Bremer, Øyvind Nordbø and Elisabeth Kommisrud - for agreeing to this second look at our data. As in the paper: the 3D camera came from the project “New traits in pigs and cattle based on 3D imaging technology”, supported by the Research Council of Norway under the BIONÆR programme (project number 282252). Thanks to Hallstein Holen and his team at the Geno performance testing station - Jan Tore Rosingholm, Erik Skogli, Sigmund Høibakken and Stein Marius Brumoen - for their time and indispensable help with data collection, and to Prof. Jane Morrell and Prof. Bjørg Heringstad for their valuable ideas and discussions.

To leave a comment for the author, please follow the link and comment on their blog: Data Science Guts.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)