Home / Insights / AI and Machine Learning

AI and Machine Learning

Computer Vision for Agriculture and Food Quality Inspection: Grading, Defects and the Data Problem

Natural products vary far more than manufactured parts, so food and produce inspection projects succeed or fail on data and evaluation, not on the model. This guide explains how to scope, test and deploy computer vision for grading and quality checks.

TopicsAI and Machine Learning

Key takeaways

  • Start from a written grading standard or defect list that your quality team already uses; a model cannot be more consistent than the definitions it is trained on.
  • Expect accuracy to drop when lighting, season, variety or camera changes: a widely cited plant disease study fell from 99.35% to 31.4% on images taken in different conditions.
  • Build the test set from your own lines, sites and seasons, keep it separate from training data, and refresh it every season.
  • Plan for a human review path for low-confidence items from day one; it protects food safety and generates the labels you need to improve.
  • Pilot one product, one defect family and one inspection point before scaling, and measure against the current manual process rather than against a vendor demo.

Agriculture and food businesses inspect enormous volumes of product by eye: sorting fruit by size and blemish, checking grain for foreign material, grading meat or seafood, confirming that packs are sealed and labelled correctly. Manual inspection is slow, varies between people and shifts, and is hard to staff at harvest peaks. Computer vision promises consistent, fast, recorded inspection, and the research base is real: a 2018 survey of 40 deep learning studies in agriculture by Kamilaris and Prenafeta-Boldú concluded that deep learning achieved high accuracy and outperformed commonly used image processing techniques.

The problem is that apples, prawns and coffee beans are not machined parts. Colour, shape and texture vary by variety, region, season and ripeness. Lighting in a packhouse is different from lighting in a field. A model that looks excellent in a pilot can quietly degrade the following season. This article is for operations directors, quality managers and CTOs at growers, packers, processors and food manufacturers who are deciding whether to build a vision inspection system, what to ask of suppliers, and how to avoid a pilot that never reaches production.

I write from the engineering side. At PoliteTech our computer vision development work covers object detection, classification, visual inspection and on-device models, with a review loop for uncertain results. The guidance below reflects how we would scope an agrifood project, and where we have seen inspection projects go wrong generally.

Where computer vision fits in agrifood quality control

Before choosing technology, map the inspection points where a decision is actually made. Vision is most useful where a person currently looks at product and makes a repeatable call against a known standard.

Common inspection tasks

  • Grading and sorting: assigning fresh produce, eggs, nuts or seafood to grades by size, colour, shape and surface blemishes.
  • Defect and disease detection: bruising, rot, insect damage, cracks or disease symptoms on individual items or leaves.
  • Foreign material detection: stones, stems, plastic or glass in bulk product. Visible-light cameras catch some of this; dense or transparent contaminants usually need X-ray or other sensors.
  • Counting and yield estimation: counting fruit on trees, plants in trays or animals in pens to forecast volume and labour.
  • Packaging and label checks: fill level, seal integrity, date codes and allergen labels on packed goods. These are closer to manufacturing inspection and are often the easiest place to start.

Why grading standards matter

Grading only works when buyers and sellers share the same definitions. The US Department of Agriculture’s Agricultural Marketing Service describes its grade standards as a common language that large-volume buyers such as retailers, restaurants and foreign governments use to make transactions easier, with trained graders reviewing product against official standards. Your model needs the same thing: a written, unambiguous standard. If two experienced graders disagree on 15% of items, the model will learn that disagreement. Measure human agreement first; it sets the realistic ceiling for automation.

Action

List every inspection point on one line or site, note who decides, what standard they use, the volume per hour and the cost of a wrong call in each direction (rejecting good product versus passing bad product). That table becomes your prioritisation tool.

Why food and produce are harder than factory parts

If you have read about vision inspection in manufacturing, the core ideas transfer, but agrifood adds variability that changes the economics. We cover the manufacturing view in our checklist for visual inspection in manufacturing; here are the differences that matter for food.

Natural variation

No two potatoes are the same shape. Acceptable colour shifts with variety and ripeness. A blemish that is cosmetic on one cultivar can signal disease on another. The model must learn what normal variation looks like, which needs many more examples than a stamped metal part.

Domain shift between conditions

The clearest warning in the literature comes from plant disease detection. Mohanty, Hughes and Salathé trained models on 54,306 images of diseased and healthy leaves and reported 99.35% accuracy on a held-out test set collected under the same controlled conditions. When the model was tested on images from trusted online sources taken in different conditions, accuracy fell to 31.4%. The lesson for buyers is direct: a headline accuracy figure means little unless the test images look like the images your cameras will capture, in your lighting, across your seasons.

Seasonality and short windows

Many crops are processed for a few weeks a year. You may get one chance per season to collect images of a particular defect, and if the camera position changes between seasons the data may not transfer cleanly. Plan data collection a season ahead of when you need the model in production.

Hygiene and environment

Washdown, humidity, dust, cold stores and vibration affect cameras, lighting and edge hardware. Enclosures, lens cleaning routines and fixed lighting are not optional extras; they are part of the inspection system.

Options: rules, classical vision, deep learning or off-the-shelf sorters

There is more than one way to automate inspection. The right answer depends on volume, product variability and how much control you need over the model.

ApproachBest forStrengthsLimitations
Commercial optical sorterHigh-volume, common products (grains, nuts, standard produce)Proven hardware, vendor support, fast throughputFixed capabilities, limited data ownership, harder to add custom defects or integrate records
Classical image processing (colour thresholds, size measurement)Size and colour grading under controlled lightingExplainable, little training data, cheap to runBrittle when lighting or variety changes; struggles with subtle defects
Custom deep learning modelSubtle defects, disease symptoms, mixed products, counting in the fieldHandles variation, improves with data, can be tailored to your standardNeeds labelled data, evaluation discipline and ongoing maintenance
Hybrid (deep learning plus rules plus human review)Most production deploymentsRules handle measurable criteria, model handles judgement, people handle uncertaintyMore integration work; needs clear ownership of each layer

How to read the table

If an off-the-shelf sorter already handles your product and defects, buying it is usually cheaper and faster than building. Custom work makes sense where your standard is specific to your buyers, where you need inspection records tied to batches and growers, where you inspect in the field or at receiving rather than on a sorting line, or where you need the model to run on a phone or tablet. Most real systems end up hybrid: measuring size with simple geometry, classifying defects with a trained model, and routing uncertain items to a person.

Sensors beyond the visible spectrum

Some quality attributes, such as internal bruising, sugar content or dense foreign bodies, are not visible to an RGB camera. Near-infrared, hyperspectral and X-ray systems exist for these, but they add cost and specialist calibration. Confirm with your quality team whether the attribute you care about is visible at all before committing to a camera-only design.

Data and labelling: the real cost of an inspection model

In agrifood projects, data collection and labelling usually cost more effort than model training. Getting this right decides whether the project reaches production.

What to collect

  • Images from the exact camera position, lens and lighting you will use in production, not phone photos taken for convenience.
  • Examples across varieties, growers or sources, times of day and the full processing season.
  • Enough examples of rare but important defects. If a defect appears once in ten thousand items, you may need targeted collection, such as setting aside rejected product and imaging it deliberately.
  • Metadata with every image: date, line, variety, batch, camera settings. This lets you diagnose failures later.

Who labels

Labels must come from people who apply your grading standard, ideally your own graders working from a labelling guide with photo examples. Measure agreement between labellers on a shared sample, resolve disagreements in the guide, and relabel. We discuss labelling budgets and quality checks in our article on image labelling quality and cost.

Keeping the test set honest

Google’s machine learning guidance recommends separate training, validation and test sets, warns that a test set must be representative of the real-world data the model will face, and stresses removing test examples that duplicate training examples because duplicates inflate results. In food inspection, near-duplicates are common: several frames of the same apple rolling past, or the same batch photographed twice. Split by batch, day or grower, not by individual image, so the test genuinely measures performance on unseen product.

For example, a mid-sized citrus packer might hold out every image from two specific harvest weeks and one grower as the test set, and train on the rest. If accuracy on that held-out set is much lower than on the validation set, the model has learned something about the training batches rather than about defects.

How to decide whether to proceed: a pilot scorecard

Treat the first phase as an experiment with clear pass and fail criteria agreed in advance. A useful pilot answers four questions: can we capture usable images, can people label them consistently, can a model match human performance on held-out data, and does it work on the line in real time?

Pilot scorecard

CriterionWhat to measureProceed if
Image qualityShare of images where a grader can make a confident callGraders can judge nearly all images without needing to handle the product
Label consistencyAgreement between two graders on the same sampleAgreement is high enough that you trust the standard; disagreements are understood
Model accuracyPrecision and recall per defect class on a held-out batchClose to human agreement on the classes that matter most
Cost of errorsValue of false rejects versus cost of false passesOperating threshold gives a better business result than the current process
ThroughputInference time per item at line speedKeeps up with peak volume with headroom
Operator acceptanceFeedback from graders and line supervisorsStaff see it as help, and the review workflow is usable

Choosing metrics

Overall accuracy hides the errors that matter. If 98% of items are good, a model that passes everything is 98% accurate and useless. Report precision and recall for each defect class, and decide with your quality and commercial teams which error is more expensive. Food safety defects, such as contamination, need high recall even at the cost of more false rejects. Cosmetic grading may tolerate more errors if the downgraded product still sells.

Implementation: from pilot to a running inspection line

Once the pilot passes, the work shifts from model accuracy to engineering a dependable system.

  1. Fix the capture setup. Mount cameras rigidly, use controlled lighting, and document positions so they can be restored after cleaning or maintenance.
  2. Choose where the model runs. Line-side sorting usually needs edge hardware for low latency; field counting may run on a phone or tablet; batch analysis of receiving photos can run in the cloud. Our article on cloud, edge or on-device computer vision covers the trade-offs.
  3. Design the confidence workflow. Set thresholds so confident decisions are automated and uncertain items go to a grader, with the image and model output shown side by side.
  4. Integrate records. Link every decision to batch, grower and time so you can trace issues, support claims and report quality by source.
  5. Run in shadow mode. Let the system make decisions without acting on them for an agreed period, compare with graders, and only then let it control rejection.
  6. Monitor and retrain. Track rejection rates, review volumes and grader overrides by day and variety. A sudden shift often means a camera has moved or a new variety has arrived, not that quality has changed.

Ownership

Decide who owns the model after launch. Someone must review overrides, curate new training data each season and approve threshold changes. Without an owner, accuracy erodes and staff quietly stop trusting the system.

Risks, costs and how to control them

Vision inspection projects rarely fail because the model cannot be trained. They fail on the surrounding factors.

Main risks

  • Overstated pilot results: a test set drawn from the same batches as training data. Control it by splitting by batch and season.
  • Seasonal drift: new varieties, growers or weather change appearance. Control it by budgeting for a data refresh and retraining every season.
  • Food safety reliance: treating a vision model as the only control for contamination. Keep existing controls such as metal detection and X-ray where they apply, and document the role of the vision system in your food safety plan.
  • Hardware and hygiene: cameras fogging, lenses dirty, lights failing. Add health checks that flag blurred or dark images.
  • Vendor lock-in: models and images held only by a supplier. Contract for ownership of your images, labels and trained model weights.

Cost structure

We do not publish prices here because they depend heavily on scope, but the cost drivers are predictable: data capture hardware and lighting, labelling time from graders, model development and evaluation, integration with line controls and quality records, edge hardware, and ongoing seasonal retraining. Many teams budget for the first three and underestimate the last two. Ask any supplier to break their proposal down along these lines.

Wider value

Better grading reduces downgrades and claims, and better records help trace problems to source. The United Nations Environment Programme notes that estimates attribute 8 to 10% of global greenhouse gas emissions to food that is not consumed, so inspection that keeps sellable product out of the waste stream has environmental value as well as commercial value. Keep claims about savings tied to your own measured baseline.

Checklist before you commission a vision inspection project

  • We have a written grading or defect standard with photo examples, and we know how often our graders agree.
  • We have picked one product, one defect family and one inspection point for the pilot.
  • We know the business cost of a false reject and a false pass for that point.
  • We can capture images with the production camera, lens and lighting, across varieties and the full season.
  • Labelling will be done by people who apply our standard, using a labelling guide.
  • The test set is split by batch, day or grower and kept separate from training data.
  • Uncertain items will go to a human reviewer, and their decisions feed back into training data.
  • Every decision will be linked to batch and source records.
  • Our contract gives us ownership of images, labels and model weights.
  • We have named an owner and a budget for seasonal monitoring and retraining.

If you can tick most of these, you are ready to scope a pilot. If not, the gaps are usually cheaper to close before engaging a development team than after.

Frequently asked questions

How many images do we need to train a food inspection model?

It depends on how varied your product is and how rare the defects are. Pretrained models reduce the number needed, but you still need enough examples of each defect class across varieties and conditions. A small pilot on one product and defect family will tell you far more than a general rule.

Can we use our existing cameras?

Sometimes. If the resolution, angle and lighting let a human grader make a confident call from the image, a model may work too. If graders struggle with the images, a model will struggle more, and new capture hardware is usually the better investment.

Should computer vision replace our metal detector or X-ray checks?

No. Visible-light cameras cannot see many dense or hidden contaminants. Treat vision as an additional control for visible defects and grading, and keep established food safety controls in place.

What accuracy should we expect?

Expect accuracy close to the agreement level between your own experienced graders, measured on held-out batches from your own lines. Be cautious of figures from demos or other datasets; research shows accuracy can drop sharply when conditions change.

Who owns the model and the data?

You should. Contract for ownership of your images, labels and trained model weights, so you can retrain or change supplier without starting again.

Sources and methodology

Guidance reflects PoliteTech delivery experience. The external references below informed specific points in this article.

  1. arXiv: Kamilaris and Prenafeta-Boldú, Deep learning in agriculture: A survey (2018) — accessed 9 November 2026. Supports the summary of 40 surveyed studies and the conclusion that deep learning outperformed common image processing techniques.
  2. arXiv: Mohanty, Hughes and Salathé, Using Deep Learning for Image-Based Plant Disease Detection (2016) — accessed 9 November 2026. Source of the 54,306-image dataset, the 99.35% held-out accuracy and the drop to 31.4% on images from different conditions.
  3. Google for Developers: Machine Learning Crash Course, Dividing the original dataset — accessed 9 November 2026. Supports guidance on separate training, validation and test sets, representative test data and removing duplicates.
  4. USDA Agricultural Marketing Service: Grades and Standards — accessed 9 November 2026. Supports the point that grade standards act as a shared language for large-volume buyers and are applied by trained graders.
  5. UNEP: Food Waste Index Report 2021 — accessed 9 November 2026. Source of the estimate that 8 to 10% of global greenhouse gas emissions are associated with food that is not consumed.

Is one of your inspection points ready for a vision pilot?

Tell us the product, the defects you care about and how you inspect today. We will help you scope a pilot with honest pass and fail criteria.