Article sections
1. First define what the dataset, not the model, will represent2. An image and an independent sample are not the same thing3. Sampling plan: Shift, batch, machine, and time variables4. Do not measure defect diversity solely by the number of classes5. Do not confuse image quality with data quality6. Metadata: Make sure you know where the image came from7. What to check on site during data collection8. Data storage, file formats, and integrity checks9. Duplicate images, near-duplicates, and poor-quality samples10. Data versioning: Which model learned from which data?11. Spending the data collection budget where it matters12. A concrete example: A data collection plan for a metal part line13. How do you decide whether a dataset is ready?14. Why are data provenance and usage rights engineering issues?15. How to make a coverage report readable16. Do not separate data preparation from production changesFrequently asked questionsBuilding a dataset for an industrial image processing project does not mean saving as many camera photos as possible. The real goal is to represent the products, defects, and imaging conditions that will be encountered in production in a structure from which the model can learn and against which it can be tested reliably. The initial data collection decision determines labeling costs, the reliability of test results, and how the system will behave across different shifts.
Consider ten thousand images captured on a metal part production line, all during the morning shift, with newly installed lighting, and from the same batch. The image count may be large, yet it may provide almost no information about a dirty camera window, a new material batch, different part placement by the operator, or variable lighting on the night shift. This is why the main indicator of a good dataset is not the raw file count but how well it covers the relevant variables.
This guide offers a data engineering framework applicable to production environments, from data collection planning and sampling design to metadata organization, data versioning, and site acceptance. Numerical examples are constructed for explanatory purposes; they do not represent actual production performance.
1. First define what the dataset, not the model, will represent
Before building a dataset, you need to establish precisely which decision you want to automate. "Defect detection" alone is not a data definition. Are you looking for a 0.2 mm scratch on a surface, identifying a missing hole, or determining whether a part is correctly oriented? Each requires different resolution, sampling, and labels. Linking the problem to a production outcome also creates a meaningful criterion for sample collection.
For example, scratches, dents, and oil stains on a connecting part may be separate classes. But the production team may regard an oil stain as cleanable and a dent as grounds for immediate rejection. If the same visual anomaly types have different operational consequences, a binary "defective/defect-free" label hides both the business rule and data diversity. First, create a defect dictionary, then examine whether each class can actually be distinguished in the image.
The dataset's intended scope must also be documented: Which product family, camera station, production line, and period? Do not assume that work on one product type can be applied directly to another that looks similar but has a different coating. Clearly stating excluded conditions at the outset prevents misinterpretation of success criteria later.
Practical output: Prepare a one-page data scope document. Include the target decision, critical defects, products within scope, excluded situations, image acquisition arrangement, and acceptable uncertainty. This document ensures that the data collector, labeler, and model developer are solving the same problem.
2. An image and an independent sample are not the same thing
When a camera captures thirty frames per second, you may not have thirty independent observations. Consecutive frames of a stationary part are almost identical apart from minor lighting fluctuations. These images increase the dataset's numerical size without adding product diversity. More importantly, splitting different frames of the same part between training and test sets can make the evaluation optimistic.
Data has natural units: product, physical part, production batch, shift, camera station, and image. A part may be photographed by multiple cameras; a single frame may contain multiple parts. Losing these relationships makes both deduplication and reliable experimentation difficult. For this reason, alongside the filename, fields such as part_id and, where appropriate, batch_id should be maintained. A unique record identifier for the camera image is also required separately.
If you do not know which object an image belongs to, you cannot easily determine the actual number of independent samples in the system. Collecting one hundred frames of a single defective part on the production line is not equivalent, for learning purposes, to collecting one frame each of one hundred different defective parts. The second option usually represents a broader range of defect forms and environmental changes; however, the first option also has deliberate uses when multi-angle imaging is required.
3. Sampling plan: Shift, batch, machine, and time variables
Instead of taking a thousand random images, design the sampling plan around the variables the dataset must cover. In practice, variables such as product family, raw material batch, supplier, machine, mold, shift, operator, light level, camera settings, and time are considered together. Fully crossing all of them is not feasible in most factories; what matters is identifying risky combinations and sampling them deliberately.
For example, three shifts and four product types yield twelve combinations of conditions. Some combinations may never occur in production. Others may correspond to times when rare but critical defects appear. Putting equal numbers of images in each cell is not automatically the best solution: the weight of a condition very common in production and the weight of a condition monitored solely because of risk serve different purposes. This is why sampling that represents production frequency and sampling that deliberately collects difficult cases must be planned separately.
Images sampled to reflect production frequency are valuable for understanding the distribution and estimating the real-world error burden. The difficult-case pool is used for learning and robustness testing. The two pools can be maintained together, but the policy used to select each sample must be recorded. Otherwise, inferences about actual defect prevalence will be distorted.
Scheduling sampling weekly or monthly helps capture new variations that emerge over time. A large dataset collected in a single day may contain no examples of sensor alignment changes after maintenance or the material appearance of a different supplier.
4. Do not measure defect diversity solely by the number of classes
Images collected under the "scratch" label may look very similar to one another. Scratches of the same length, direction, and brightness become a single visual pattern for the model. Real scratches, however, can vary in length, width, direction, intensity, location, and background texture. These subcharacteristics should also be tracked when representing a defect family.
To describe defect examples, a defect taxonomy and, if necessary, attribute fields can be used. Fields such as type, severity, size range, location, part region, visibility, repairability, and expert uncertainty facilitate later analysis. It is important to base the severity scale on a measurable business rule. If the boundary between a "small scratch" and a "medium scratch" is not defined anywhere, labelers will produce different results.
Deliberately scratching parts or adding stains can sometimes be used in feasibility studies to collect defects. However, these images must be marked separately from real production defects. A human-made scratch and a mark left by the production mechanism may differ microscopically and optically. Synthetic or controlled defects do not fully replace real defects.
An important distinction: A visually difficult example is not necessarily operationally critical. A shiny but acceptable machining mark may be difficult for an algorithm, while a very small crack may be safety-critical. Both the situations the model struggles with and the cost of missing a defect should determine collection priorities.

5. Do not confuse image quality with data quality
Sharp, evenly lit, high-resolution images may be preferred, but not every "perfect" image is good data. If imaging conditions are not representative of production, technically clean images can make reality appear easier than it is. Conversely, some production lines operate with slight vibration, reflections, or changes in product position. If the system will be used under these conditions, the images must include those variations as well.
Nevertheless, a minimum image quality threshold is needed. You may want to automatically remove completely out-of-focus frames, frames cut off because of a trigger error, or dark frames captured when the light went out. Before deciding, consider what these situations mean on site: it may be safer to mark a faulty image caused by a camera failure as an acquisition error rather than pass it through the model as a "normal product."
During imaging, information such as focus, exposure time, analog gain, light output, trigger source, and camera firmware should be fixed or monitored. If a parameter changes, image appearance can change too. Without recording this change, it becomes difficult to determine later whether a drop in model performance is due to the data or the algorithm.
If automatic white balance or automatic exposure is enabled on the camera during data collection, remember that a fixed surface may look different from one recording to another. This automation may be necessary in some applications, but the settings must be managed in a production-appropriate, repeatable way.
6. Metadata: Make sure you know where the image came from
Metadata is accompanying information describing the context in which an image was produced. Although filenames or folder paths may provide some clues, sustainable systems maintain this information in explicit fields. A simple but useful record may include a unique image identifier, capture time, part identifier, batch identifier, product code, camera station, camera settings profile, shift, whether operator information is needed, and label status.
Each field has a data privacy and operational cost. A role or anonymous shift code is often sufficient instead of an operator's name. The goal is not to collect personal data but to obtain information that can explain image quality and error distributions. Making the metadata schema overly complex from day one can cause teams to leave records incomplete. First make the fields that are actually used mandatory, then add others as needs arise.
Establish a time zone and synchronization policy for timestamps. If different camera clocks drift by a few seconds, matching images of the same part or tracing a production event becomes difficult. Consistent clocks and keys are needed to combine an image, a PLC event, and a quality inspection record on site. If no part identifier exists, a conveyor trigger counter or a station-local sequence number can be used temporarily; the limitations of this solution must be documented separately.
Using metadata as model input is a separate decision. Some fields are for auditing only. For example, if a product's final quality inspection result is added to the image record afterward, accidentally including that field in the training input can cause target leakage.
7. What to check on site during data collection
Data engineering is not done only at a computer. Physical factors such as camera mounting, luminaire position, lighting adjustment, seating the product in its fixture, and the cleaning cycle directly affect the image. Rather than taking a few sample pictures and viewing them on screen during the first site visit, it is more meaningful to run short recording sessions at actual production speed, with different products, and under normal maintenance conditions.
Assess repeatability by examining consecutive frames of the same part. Does sharpness remain constant when the product position changes? Is the light distribution similar in every frame? Is exposure affected when camera temperature or line speed changes? Are the boundaries of the suspected defect visible in every frame? The answers guide subsequent data collection.
Some defects are visible only from particular angles. In such cases, a single camera image may be insufficient, regardless of its resolution. Instead of adding more similar frames to the dataset, consider another camera, a different lighting angle, or mechanical reorientation. The task of data collection is not merely to accumulate the images currently available; it is also to question whether the necessary information is present in the image.
Do not overlook production line safety rules either. Activities such as creating controlled defects, returning a part to the line, or opening a protective cover must only be carried out using procedures approved by the business. Safety or traceability must not be compromised for more data.
8. Data storage, file formats, and integrity checks
The compression format of original images can matter. Lossy JPEG compression can create artificial patterns around fine scratches or low-contrast stains. Lossless formats such as PNG can be advantageous for some measurement and defect analyses despite higher storage and transfer costs. RAW or manufacturer-specific formats can preserve sensor data but introduce tooling and maintenance complexity. There is no single correct format; choose according to defect scale and intended use.
Prevent images from being silently overwritten. Preserve original files in a read-only area, and have operations such as cropping or color correction produce new derived files. Image identifiers and file hashes can detect corrupted transfers or accidentally modified records. These integrity checks are particularly important in projects where data moves between different disks, machines, or teams.
Directory structure matters as much as the recording format. Although sorting files only into good/ and bad/ folders is easy for short-term experiments, information such as part identity, camera profile, and label version may be lost. The file path should represent physical storage, while the metadata table should represent logical relationships. Treating them as the same concept makes migration and versioning harder in the long term.
Site infrastructure is not always uninterrupted. Where will images be stored temporarily if the connection between the camera and central storage fails? If the queue fills up, which records will have preservation priority? How will duplicate records be prevented during retransmission? These are data engineering decisions in the traditional sense and must be resolved well before the model.
9. Duplicate images, near-duplicates, and poor-quality samples
Finding identical files is easy; finding near-duplicates is harder. Images of the same part captured a few milliseconds apart or slightly cropped are different at the file level but carry largely the same information. A perceptual hash such as pHash, image similarity, or feature vectors can flag potential duplicates. However, deleting every automatically flagged pair may be wrong; two different defects can produce similar images.
Decisions about duplicates must align with the production objective. If multiple images are needed to inspect a part from different angles, preserve those frames but record that they belong to the same group. Deleting similar examples based solely on appearance during data cleaning can inadvertently reduce rare defect subtypes, hard negatives, or the natural production distribution.
It is useful to establish three categories of quality issues: technically unusable images, borderline cases requiring review, and natural variation expected in production. The first category may be a direct acquisition error. The second remains in the quality review pool. Removing the third merely because it is difficult can reduce the model's fit to real site conditions. Data cleaning rules must be measurable, and the number of examples removed for each reason must be reported.

10. Data versioning: Which model learned from which data?
A dataset is a living entity. As new products arrive, the line camera is readjusted, or defect definitions change, the data changes too. Continually adding files to a single folder is not enough. Each major data version should explain which examples it contains, the label schema, split policy, cleaning decisions, and why it was created.
For example, v1 may represent the initial site collection, v1.1 the version in which missing metadata was completed, and v2 the version adding a new product family. Version numbers alone are not enough. In particular, changes affecting the training/test split or labels can invalidate model comparisons. Release notes must therefore include both numerical changes and their impact on evaluation.
Recording the data snapshot, label revision, and preprocessing settings used in a training experiment makes it possible to compare results months later. Data changing through an update should not be a reason why a previous experiment cannot be reproduced. This traceability is a prerequisite for understanding whether a model update genuinely improves performance.
11. Spending the data collection budget where it matters
When the budget is limited, trying to produce the same number of images for every class can seem attractive. But the greatest benefit does not always come from more images. Sometimes a single night-shift session provides more valuable information than ten thousand similar daytime images. Sometimes the defect definition needs clarification rather than another round of photographing defective parts.
When evaluating a collection request, consider these three criteria together: the probability of encountering the condition in production, the model's current uncertainty, and the cost of a decision error. A high-risk but very rare crack may require a dedicated collection process. A very common but noncritical natural color variation may also matter because it determines the false alarm rate. Managing both needs with the same "defect count" target is not sound practice.
Do not consider labeling costs separately from the collection budget. Thousands of new frames produced in one second become expensive if every image requires expert review. Methods such as clustering, prescreening, and uncertainty-based candidate selection can help determine which examples should be reviewed first. However, the risk of a rare defect being lost in an automatic filter must be reduced through human sampling and auditing.
Treat data collection as a learning process, not a one-off project step. The initial dataset provides a starting point; site feedback reveals missing conditions; targeted collection fills the gaps; and the new version is reevaluated under independent conditions.
12. A concrete example: A data collection plan for a metal part line
Imagine a factory inspecting four metal connecting parts from the same product family. Suppose the line has two cameras and three shifts. Let the production team define scratches, dents, missing holes, and acceptable machining marks separately. The first task is not to write "50,000 files" as the image collection target but to create a coverage table showing which combinations of parts and defects have been observed under which conditions.
Initially, normal images for each product type are collected from different shifts and batches. Defective images are selected from all available natural processes, and which defect belongs to which part is recorded. If a part is imaged by two cameras, a shared part identifier is used. Acceptable machining marks are specifically set aside because they are hard negatives that may increase false rejections later. If lighting changes on the night shift, the lighting profile is recorded; if the effect is large, stabilizing the hardware is the priority solution.
At the end of the first two weeks, examine gaps in the coverage table rather than the total count. For example, only two product types have images from the third shift; dents come from only one batch; there are no normal examples of the new coating. Subsequent collection sessions fill these gaps. Experts review uncertain images separately; those for which a rejection decision cannot be made are not used as definitive ground-truth labels.
Some production batches are set aside for evaluation from the outset and are not mixed with training examples. This allows testing of the model's behavior on new parts rather than its memorization of the same part. Recording all decisions with the data version also makes it possible to see the impact of the next change.
13. How do you decide whether a dataset is ready?
A dataset being "ready" does not mean it contains every possible defect. In practice, the goal is to create a starting point reliable enough to begin learning and evaluation at a defined scope and risk level. Reporting only the total image count and defect rate is insufficient. The product families, camera stations, shifts, production batches, and defect subtypes covered should be reviewed together.
The checklist should include a traceable identifier for every example, verified file integrity, an approved defect dictionary, separate handling of acquisition errors, management of duplicate examples through group identifiers, protection of test data in the collection plan, and flagged label uncertainty. Empty cells may be consciously accepted, but these limitations must be stated in the datasheet.
An example of measurable acceptance: Suppose the entire target product family is within scope, camera profiles are recorded, the part group is known for every image, and batches reserved for testing are isolated from training. These do not guarantee a model's success; they only make experiments interpretable. Especially where sufficient test evidence is lacking for rare, high-risk defects, the result must not be generalized as "successful."
The most valuable task before collecting data is to write down the question you ultimately want to answer: "Can this system find critical defects in a new production batch at an acceptable false rejection cost?" If the dataset design is not suited to answering that question, subsequent model improvements will pursue the wrong target.
14. Why are data provenance and usage rights engineering issues?
A dataset being technically accessible does not mean it can be used for every purpose. Supplier images may contain trade secrets; a serial number on a product may reveal customer or production information; the license of an open academic dataset may restrict commercial use or redistribution. Data source, acquisition method, permissions, and retention policy must therefore be maintained as part of the technical inventory.
Provenance must not be lost when a new derivative is created from a source dataset. For example, cropping an open-source image, applying a color space conversion, or adding a mask does not free it from all usage restrictions. Similarly, separate permission may be required to use the factory's own images in a customer presentation or a public blog. Anonymizing images and obscuring product identifiers is sometimes enough; at other times, the image itself is commercially sensitive.
One useful research example is the MVTec AD dataset. It is frequently used in anomaly detection studies because it provides defect-free training images and both defective and defect-free test examples. However, the license on its official page restricts commercial use, so the license terms must be read before incorporating the dataset directly into your own product. You must not assume that results obtained on a benchmark represent the material and lighting conditions in your own factory either.
Think of this section as a data governance check rather than legal advice. If source documentation, usage permission, retention periods, access rights, and deletion procedures are not clarified, technical teams may need to collect data again later.
15. How to make a coverage report readable
A dataset can be summarized in a single table, but numbers alone can mislead. For example, "5,000 defective images" sounds impressive. If 4,600 are of the same scratch type and the remaining 400 come from only one production batch, they may in fact represent a very narrow defect universe. It is therefore more useful to add cross-tabulations such as product-defect, shift-camera, and batch-defect alongside one-dimensional class counts in reports.
The report can be prepared in three layers. The first gives the total number of independent parts, image count, defect types, and label status. The second shows coverage by production context. The third summarizes missing cells, questionable labels, and critical cases requiring more data. These three layers support both a manager's quick reading and the engineers' detailed examination.
Representing a missing cell as zero also has implications: was the condition never observed, or does it never occur on that line? For example, if a particular product type is made only during the day, an empty night-shift cell may not be a data defect. To show this distinction, mark "not applicable," "not collected," and "collected but no defect observed" separately. Representing all three with the same zero can lead to incorrect collection priorities.
16. Do not separate data preparation from production changes
When a camera changes, everyone notices that a new sensor has arrived. A new surface coating, grinding procedure, or cleaning chemical, however, may create a smaller but systematic change in the image. For the model, these changes are also new domain conditions. Without a regularly shared change log between production engineering and the data team, understanding why model performance deteriorated may require lengthy retrospective analysis.
Product revisions, mold changes, lighting maintenance, camera firmware updates, and line layout changes should therefore be matched to dataset logs. Not every change requires retraining the entire system. First, collect a small but representative validation set from the relevant condition and compare results against the existing baseline. If the change is significant, create a new data version; if it is not critical, record the rationale for the decision.
Data responsibility must also be clear in the organizational process. Who will investigate lost images, correct faulty metadata records, and approve changes to the label dictionary? If these questions remain unanswered, a technically well-designed dataset can quickly become a disorganized pile of folders. Data engineering begins before the model but continues throughout its production lifetime.
Once the dataset is prepared, do not leave it in a format understood only by the computer vision team. Prepare a one-page summary for the production and quality teams, clearly showing which products are covered, which defects are underrepresented, which camera profiles were used, and when new data is needed. Such a summary makes model performance discussions more concrete.
Frequently asked questions
How many images should a dataset contain?
There is no single number. Defect visibility, product diversity, imaging stability, model family, and the target confidence level all affect the need. Initially, measuring coverage of risky conditions, the number of independent parts, and groups reserved for testing is more meaningful than counting images. The target data quantity can be updated as learning curves and site results become available.
What should we do if we cannot find defective examples?
First investigate the mechanism that produces the defect and the available records. Controlled defect creation, human review, and anomaly detection that learns from normal data are options to consider. Because synthetic defects are not complete equivalents of real defects, validation with independent real examples remains necessary.
Can we relabel production images later?
Yes. Label definitions can be improved if original files and label versions are preserved. However, repeatedly examining the same test set and allowing it to guide training decisions diminishes its value for independent evaluation. Record the reasons for label revisions and which examples they affect.
Is a large, imbalanced dataset useful?
The natural imbalance of production data carries information; it is not an error on its own. What matters is defect coverage, label quality, test independence, and decision costs. Imbalance may require different training strategies, but losing natural prevalence in the test set can lead to misinterpretation of actual performance.
Sources and technical references
The links are primary dataset and tool documentation relevant to the topic. Illustrative numbers and original drawings are used for educational purposes in the indicated sections.