Article sections
How does deep learning interpret images?How does an image become a learnable representation rather than just a matrix?What does convolution do?Why does the receptive field matter?Pooling, stride, and loss of resolutionStrengths and weaknesses of CNNsHow does a Vision Transformer process an image?What does an attention map actually tell us?How do the backbone and task head differ?When does transfer learning help?How do you choose between a CNN and a ViT?How can we identify shortcut learning?Example engineering scenario: fine scratch inspectionQuestions to ask when choosing an architectureMathematical foundations: convolution and efficient parameter sharingAn intuitive view of ViT computational costWhy were multiscale architectures developed?How can representation learning and class separation be tested?A controlled experiment for moving from a baseline to a new architectureHow can field observations and model analysis be combined?Frequently asked questionsVisual sourcesCNN and Vision Transformer architectures, convolution, attention mechanisms, feature extraction, and architecture selection for manufacturing problems. This guide examines the assumptions behind these methods, the conditions in which they can be used, the reasons they fail, and the decision points encountered in production.
How does deep learning interpret images?
Short answer: Rather than making sense of an image as a human does, deep learning uses multilayer representations computed from pixels and modified during training. Early layers may emphasize cues such as edges, color transitions, and local texture; later layers may emphasize shape, relationships between parts, and task-specific discriminative patterns. What these representations actually encode depends on the architecture and training data. A network producing the correct label does not, by itself, prove that it found the defect for the right reason.
Suppose a camera photographs two metal parts on a production line. One has a fine scratch; the other only has a reflection. A person can distinguish them using the surroundings of the part, the direction of the light, and the expected surface texture. For a learning system to make the same distinction, its training data must cover both situations, the defect must be sufficiently visible in the image, and the architecture must preserve the relevant spatial detail. The model's output depends on all these conditions together.
In traditional image processing, engineers often define which features to look for: thresholds, contours, circularity, edge density, or color differences. In deep learning, the training loss and data largely determine which intermediate features are useful. This can make method development easier, but it also increases the risk of obscuring the variables the model relies on and the reasons it fails.
How does an image become a learnable representation rather than just a matrix?
A digital image is a two-dimensional array of numbers in grayscale and, for color images, usually a tensor with three or more channels. For example, a 1024 × 1024 RGB image contains 3,145,728 raw channel values. This number describes only the volume of input data; it does not mean that an algorithm has extracted meaningful features from those pixels. A network aims to transform the raw pixel arrangement into numerical representations that are more useful for making decisions.
Normalization adjusts the numerical scale of pixel values. It does not, however, resolve problems such as an incorrect color channel order, the sensor's automatic white balance, JPEG compression, or the camera's gamma transformation. Using BGR in a model's training images and RGB in production can disrupt even a network that has learned useful color features. Data preprocessing steps should be versioned as an integral part of the model and applied identically in production.
A camera image is not the object itself; it is the combined product of the lens, lighting, surface, and sensor. A bright spot may therefore be a genuine metal defect or a reflection from directional lighting. If every bright spot is associated with a 'defect' label throughout training, the model may learn an incorrect shortcut. The solution is not always a larger network, but counterexamples and control of the physical scene.

What does convolution do?
A convolutional neural network applies small numerical kernels to different regions of an image. One kernel may become sensitive to vertical edges, another to local texture or color changes. In traditional image processing, an engineer specifies the Sobel kernel; in a CNN, the coefficients of many filters are generally learned through optimization. In practical terms, this allows similar local patterns to be recognized at different positions in an image.
A layer's output width depends on the input size, padding, stride, and kernel size. Knowing only 'how many layers' are used is not enough. Operations with a stride of 2, for example, reduce the spatial dimensions. If a defect is initially 5–6 pixels wide, very little positional information may remain after successive downsampling operations. Gaining context can be useful for classification, but this loss is a serious problem for fine scratch segmentation.
Convolution alone does not contain concepts such as 'screw,' 'breakage,' or 'scratch.' These concepts emerge from the interaction between patterns represented by different layers and the task head. Nor is there any guarantee that the same neuron represents the same physical cause in different examples; claims such as 'this filter is definitely a scratch filter' require careful analysis to be defensible.
Why does the receptive field matter?
The region of the input image that can influence an output unit is called its receptive field. Small receptive fields are suited to capturing fine textures, while large receptive fields can carry information about the whole part, neighboring components, and context. Finding a crack in a screw head requires local detail; determining whether three screws are missing from an assembly may require broader context.
The theoretical receptive field is calculated from the connections between layers. In practice, the effective receptive field may often be narrower and more concentrated at the center. This distinction means that theoretical values in architecture documentation should not be confused with actual detection behavior. Small defects becoming diluted within the network when a high-resolution image is classified as a single image is related to this issue.
Dividing images of large parts into small image regions (patches) can make local defects easier to detect. However, this may discard logical relationships between patches and information about scale. A patch may be sufficient for a scratch, for example, but not for identifying a screw in the wrong position. The requirements for local and global context therefore need to be derived from the application problem.

Pooling, stride, and loss of resolution
Pooling reduces spatial dimensions by summarizing neighboring values. Max pooling uses the highest activation, while average pooling uses the mean. Strided convolutions can partly serve the same function. Lower resolution reduces computation and memory costs but makes the location of small details less precise. If a model is expected to reliably find defects measuring a few millimeters, image scale, backbone stride, and annotation resolution must be examined together.
For example, a defect 12 pixels wide corresponds to roughly three sampling units in a network that halves the image dimensions twice. This is only a rough geometric analogy; actual representations change through interpolation and filtering. Nevertheless, it illustrates a measurable engineering limit: if a physical defect does not cover enough pixels to begin with, later layers cannot be expected to magically recover it.
Strengths and weaknesses of CNNs
CNNs provide a strong starting point for local patterns, shared filters, and hierarchical feature extraction. Suitable tools, lightweight models, and well-optimized inference libraries are available for many production scenarios. CNN-based solutions can be practical, particularly where classification or segmentation is clearly defined and images are captured repeatedly under controlled conditions.
However, the advantages of a CNN cannot be reduced to 'working well with little data.' Results depend on pretraining, data augmentation, architecture, image size, and the task. It is equally incorrect to say that all CNNs are faster or use less memory than ViTs. Because of their operation types, two models with the same parameter count can exhibit very different latencies on different hardware.
In practice, the first step is to establish a clearly defined CNN baseline. A baseline provides a fixed point of comparison for evaluating new, eye-catching architectures. Comparing two models' scores without exactly the same data split, input resolution, and measurement method is technically misleading.
How does a Vision Transformer process an image?
A Vision Transformer (ViT) divides an image into patches of a specified size and represents each patch as a numerical token. With positional information added, these tokens interact in attention layers. This enables the model to establish relationships between visual cues in distant regions. This aspect of the original ViT is particularly notable for tasks that require broad context.
However, a ViT does not directly understand the physical world either. With a patch size of 16 × 16, a defect only a few pixels across may remain a weak signal within a single token. At very high resolutions, the number of tokens and the cost of attention can increase; some modern architectures use window-based, hierarchical, or more efficient attention schemes. The claim that 'Transformers always deliver higher accuracy' is therefore indefensible.
Claims about ViT data requirements need to be considered specifically in the context of training from scratch. A strongly pretrained ViT can perform well on small target datasets through transfer learning. However, visual representations learned from natural images may not match the representational requirements of fine defects on metal surfaces, making experiments in the new domain essential.
What does an attention map actually tell us?
Attention weights are internal computational coefficients indicating how much weight a token gives to other tokens. They are not automatically the rationale for the model's decision or a reliable explanation of a defect's location. When multilayer attention, residual connections, and the task head are combined, the causal interpretation of a single map remains limited.
A similar warning applies to visualization methods such as Grad-CAM. Even if a map highlights a region near the defect, whether removing that region changes the model's decision must be tested separately. Occlusion, counterexample, and ablation analyses can be used for this purpose. The key engineering question is not whether the map looks attractive, but whether the model makes the intended physical distinction.

How do the backbone and task head differ?
A backbone is the main architecture that extracts features from an image. For classification, object detection, or segmentation, these features are passed to a task-specifichead. The same backbone can be used to produce a single label in one application and boxes or pixel masks in another. When a model name is mentioned, it is therefore important to ask not only about the backbone, but also about the task head and output format.
The corresponding production-line decision is really about output requirements before model families. A single label may be sufficient to classify a product as conforming or defective. If the coordinates of a defective region must be sent to a repair station, object detection may be necessary. If the physical size of a defect area must be calculated, segmentation may be more appropriate. A model that does not match the task may fail to produce usable results despite high accuracy.
When does transfer learning help?
In transfer learning, a model's previously learned weights serve as the starting point for a new task. If pretraining transfers useful representations of visual edges and textures, rapid progress may be possible with few labels. However, transfer performance may decline as the domain gap grows. Features learned from everyday objects need validation, particularly in domains such as UV imaging, thermal cameras, or microscopic metal surfaces.
A reasonable experimental sequence is to train only the final layer initially, gradually unfreeze the final blocks, and, if necessary, fine-tune the entire network at a low learning rate. This sequence is a hypothesis, not a rule. With very little data, unfreezing the entire network can increase the risk of memorization; with abundant data and a large domain gap, training the head alone may be insufficient.
How do you choose between a CNN and a ViT?
The first requirement is two comparable systems measured on the same task. Rather than recording validation accuracy alone, record together the number of genuine defects missed at a low defect prevalence, the rejection of conforming products, latency per image, memory consumption, deployment stability, and retraining cost. Camera stability and lighting variability also affect performance independently of the architecture.
| Selection criterion | CNN-based starting point | ViT / hybrid starting point |
|---|---|---|
| Small-scale local texture | Strong starting point; preserve scale in early stages | Choose patch size carefully |
| Relationships across a wide scene | May require a larger receptive field or multiscale design | Attention can naturally handle long-range relationships |
| Pretraining | Widespread, mature options | Strong self-supervised pretraining options |
| Edge deployment | Many optimized variants available | Hardware and token costs must be measured |
| Explainability | Grad-CAM alone is not proof | Attention alone is not proof |
Another common measurement error is neglecting model loading, data transfer, and preprocessing time. A model that appears fast on a server may not fit in an edge device's memory or may take longer than expected on its first invocation. Actual cycle time must be measured end to end.
How can we identify shortcut learning?
Shortcut learning occurs when a model uses another cue incidentally associated with the label instead of the intended defect. For example, if all defective examples were captured on the night shift and normal examples came from the day shift, the network may use lighting as a proxy for defects. The same issue can arise through an annotation marker, file size, background color, or camera angle.
High training accuracy alone will not reveal this error. Tests that separate defect and shift variables, counterexamples with altered backgrounds, recapturing the same product under different lighting, and group-based data splitting are more useful. When a low score is observed, moving to a larger model should not be the first reflex; the data generation chain should be examined.

Example engineering scenario: fine scratch inspection
Suppose an image of an aluminum part is 2400 pixels wide and the visible width of the part is 120 mm. The approximate scale is then 20 pixels/mm. If the minimum scratch width is 0.2 mm, it corresponds to approximately four pixels in the image. This does not guarantee that the defect will be detected; optical MTF, focus, surface reflection, and annotation accuracy determine detectability. It does, however, provide an initial physical lower bound for the architecture to be selected.
When a classification model downsizes the entire image, the scratch may shrink to less than a few pixels. Higher resolution, a patch-based approach, or a multiscale feature map could be considered. Each introduces new trade-offs in speed and false alarms. The best solution may be to establish lighting that distinguishes scratches from normal machining marks before changing the model family.
An appropriate comparison for this scenario could be designed as follows: baseline A, traditional edge/contrast analysis; B, lightweight CNN classification; C, patch classification with a pretrained CNN; and D, a ViT-based patch approach. Testing uses the same production batches. Results show not only image accuracy, but also how many genuine defects are missed and how many conforming parts are unnecessarily diverted during a shift. This makes method selection concrete.
Questions to ask when choosing an architecture
A sound technical assessment should answer these questions: For which physical defect is the minimum size known? How many pixels does this defect cover on the sensor? Is the model's output unit a product, a patch, or a pixel? Do the images share camera or batch relationships? How similar is the pretraining domain to the target application? Is output calibration adequate? Which error cost was used to select the threshold? Have lighting and surface conditions outside the laboratory been tested?
Until these questions are answered, the 'CNN or Transformer?' debate is premature. Architecture selection should be a scientifically testable hypothesis, not a brand choice made before collecting data. A model's success in production combines an appropriate representation of the problem with technical feasibility.
Mathematical foundations: convolution and efficient parameter sharing
To understand the basic idea behind a convolutional layer, consider a 3 × 3 filter operating on a three-channel image. Each filter learns a total of 27 values across the three input channels and, in most implementations, a bias term. Because the same filter is used at different positions in the image, a separate parameter set is not assigned to every position. This is called weight sharing. It is a strong inductive bias for line, edge, and texture patterns that recur in local regions. It also explains why some CNNs learn local patterns in large images efficiently.
However, we should remember that a single small filter is insufficient to represent the relationship between two distant parts. As the number of layers increases and stride/pooling operations are used, the image region that influences the model grows. This growth is not always physically meaningful, though. If features seeing opposite ends of a long scratch are not sufficiently linked in intermediate layers, the model may not consistently capture scratch length. A feature layer with broader context or explicit geometric postprocessing may then be necessary.
The mathematical output of convolution is formed by summing the products of an input window at a particular position and the learned weights. An activation function adds nonlinearity after this linear operation. Batch normalization or layer normalization affects the numerical behavior of optimization. The presence of these layers alone does not mean that the model will generalize better. In particular, differences in normalization behavior between small-batch training and production can degrade results. The deployed model must be verified to run in evaluation mode.
An intuitive view of ViT computational cost
Dividing a 1024 × 1024 image into 16 × 16 pixel patches produces approximately 4096 tokens. In standard full self-attention, the number of interactions between token pairs grows with the square of the token count. Here there are approximately 16.8 million possible token pairs; this number describes only the attention matrix size, not the full hardware cost. Doubling the input resolution in both the horizontal and vertical directions can quadruple the token count and increase the square matrix size by roughly sixteen times. Architecture selection for high-resolution industrial images therefore cannot be separated from memory planning.
Modern ViT families do not always use this straightforward form of full attention. Window-based attention, multiscale architectures, pooling, or other efficient attention mechanisms can reduce computational cost. However, a model being a 'Transformer' does not mean that resolution constraints disappear. If a product surface has submillimeter defects, the amount of detail preserved at each stage of the model must be tested directly.
Embedding dimension, the number of attention heads, and layer depth matter as much as token size. Increasing these variables can change the parameter count and computational load. The most suitable values are determined not by a model family's catalog name, but by the detectable scale of the defect and the constraints of the device used. A model that does not fit on the GPU or is delayed by memory copying may be unsuitable for production despite a high laboratory score.
Why were multiscale architectures developed?
The same meaningful object can appear at different scales in images. The corner of a large metal sheet, a microscratch, and a screw hole cannot be processed with equal representational capacity at a single resolution level. Structures such as Feature Pyramid Networks aim to access both high-resolution local information and broader semantic context by combining feature maps from different depths. How this is achieved varies by architecture family; a simple stack of layers is not equivalent to a multiscale design.
For fine defect detection, more abstract high-level features are not always an advantage. As the network learns stronger product context, scratch boundaries may disappear. Strong preservation of early-stage features or renewed high-resolution prediction in specific regions may be necessary. The latency cost of these options should be measured during design.
Data augmentation can partly address scale issues. However, a model cannot be expected to detect a real 0.1 mm crack after resizing has removed it entirely from the image. The pixel footprint of the smallest defect must therefore be calculated alongside the crop, resize, and interpolation operations used during training. The problem concerns the entire image information chain, not just the model architecture.
How can representation learning and class separation be tested?
Visualizing a network's feature vectors after reducing them to two dimensions can offer an idea of where examples cluster. However, clusters appearing separate in PCA, t-SNE, or UMAP output does not mean that actual physical defects are definitively separated. The dimensionality reduction algorithm's parameters and random seed can affect the result. More importantly, a colorful two-dimensional plot does not preserve all actual high-dimensional distances.
A more useful experiment is to inspect nearest-neighbor images for normal and defective parts, for example. Do a defective example's nearest neighbors share the same defect type, or merely the same lighting conditions? If neighborhoods are determined by batch, camera, or background, the model may be learning the wrong representation. Production failures can often be diagnosed faster with simple visual checks like these.
Even when clusters separate in embedding space, the task head's decision threshold may be wrong. The discriminative power of the feature representation, score calibration, and final product decision should be distinguished. This allows a more meaningful investigation of whether poor performance originates in the backbone, the classifier, or the acceptance rule.
A controlled experiment for moving from a baseline to a new architecture
An experimental protocol can be established as follows. First, fix the camera setup and data split. Then select the lightest technical baseline and make the training, validation, and test workflow reproducible. Next, change only one variable: switch the backbone from a CNN to a ViT, or increase the input resolution. If augmentation, optimization, and architecture are changed simultaneously, it becomes difficult to identify the source of any improvement.
Rather than keeping a single metric, record detection by defect type, false rejections, p95 latency, model size, memory, and failed examples. Run a dedicated test on a predefined subset of small defects. Requiring the same parameter budget for every model may not always be appropriate, but the constraints held equal must be stated explicitly for the comparison to be fair.
The conclusion should not be a general statement such as 'ViT is better.' It should instead say, for example, 'For this manufactured part, at the specified resolution and operating conditions, the ViT-based solution performed better under the defined error costs.' Production engineering decisions are meaningful within these limits of scope.
How can field observations and model analysis be combined?
Incorrect predictions should be linked to the actual production context rather than stored only as data files. If errors concentrate at particular times, in a particular supplier batch, or on a particular machine, the image structure seen by the model may be the cause. With properly maintained observational data, error analysis goes beyond AI optimization and becomes an exercise in mechanical, optical, and process engineering.
Sometimes the examples a network misses are physically underlit. In that case, correcting the lighting geometry rather than extending training is the appropriate intervention. Sometimes surfaces that trigger false alarms were produced with a new grinding tool. That calls for a data collection plan representing the new normal examples. Grouping errors by production conditions makes this distinction visible.
A model being 'intelligent' does not mean that a correct quality policy emerges on its own. The best architecture is one supported by product tolerances, field data, reliable testing, and a traceable decision mechanism. In this framework, CNNs and Transformers are not absolute alternatives to each other, but tools to evaluate for the problem at hand.
Advanced engineering details to consider in production
Where is image information lost?
Increasing a network's layer count does not recover detail that was never captured by the sensor. A defect that appears ten pixels wide in the camera image shrinks to approximately two or three pixels when the input is reduced by a factor of four. If stride is used in the network's first layers, this detail may disappear before reaching higher layers. Treating image resolution merely as a training parameter related to GPU memory is therefore dangerous. Input scale should be selected together with the actual contrast delivered by the lens and the lighting conditions. For fine scratches, regional cropping, multiscale inference, or a narrower field of view at a fixed working distance may be better starting options than downsizing the full image.
Fair experiments when comparing CNNs and Transformers
Matching parameter counts alone is not enough when comparing two architectures. The size of the pretraining dataset, resolution, augmentation intensity, optimizer, runtime, and inference environment also determine the outcome. Experiments with three seeds on the same data split can reduce the misleading effect of a single best run, but they do not eliminate distribution shift on the production line. The comparison report should separately present critical-defect performance, false alarms on conforming examples, GPU/CPU latency, memory use, and consistency across shifts. Rather than reducing architecture selection to a single ranking table, evaluate it against the error costs of the target application.
The physical meaning of features
Simple structures such as edges, local contrast, and orientation may dominate early filters; in later layers, combinations of these become representations related to product shape or material texture. Nevertheless, attaching a 'scratch neuron' or 'screw neuron' label to a feature map is often an overly definitive interpretation. The same channel can respond to multiple visual features, and different channels can take on similar roles in different training runs. Feature visualizations are useful for understanding model behavior, but they do not replace a causal explanation of a decision. In production, these visuals can be used to investigate textures shared by examples that trigger false alarms.
Viewing backbone selection from a production perspective
A backbone's performance should be assessed not only through public benchmark scores, but also together with the task layer attached to it. Object detection, for example, requires multiscale maps, whereas a single vector may suffice for an image classification application. Preserving spatial detail is important in a system that produces fine-grained anomaly maps. On an embedded device, memory access cost can be more decisive than FLOP count for some operations. A benchmark report should therefore include the actual input size on the target hardware and end-to-end timing, including preprocessing. In engineering, the best architecture is often not the largest model, but the one that meets the error budget and can be deployed sustainably.
Application scenario: an architecture experiment for surface defects
Suppose the task is to find scratches 0.2 mm wide in 6-megapixel images of the same metal plate. Reducing the model input to 640 pixels may substantially reduce the visible width of the defect. First verify physical visibility, then compare single-stage classification, local patch representations, and higher-resolution feature maps as separate baselines. Rather than a single score, report critical scratch detection rate, false alarms on conforming parts, end-to-end latency, and variation across days with different lighting conditions.
Field test checklist
- Is it documented which tests were kept independent by product, shift, and capture conditions?
- Have failures correctable by the algorithm alone been distinguished from those requiring optical or process changes?
- Has it been verified that the model score does not replace physical acceptance criteria?
- Are input resolution, model version, threshold, and operating hardware held fixed in the experiment records?
- Are illustrative visuals clearly distinguished from actual measured model results?
- Are false rejections, missed defects, latency, and reinspection workload reported separately?
Frequently asked questions
What is the main difference between a CNN and a ViT?
CNNs extract hierarchical features using local convolutional filters. A ViT establishes attention relationships between image patches. Both families can learn context at different scales; their performance depends on data, pretraining, and hardware.
Does a Transformer detect small defects better?
There is no such guarantee on its own. Detail may be preserved or lost depending on defect size relative to patch size, input resolution, and the multiscale structure used. Physical detectability must be tested first.
Is a feature map the same as a model explanation?
No. A feature map shows intermediate activations; an explanation claims which cue the model used to make its decision. The latter claim requires independent testing and counterexamples.
How many layers should the network have?
There is no single correct number. Start with a simple, measurable baseline and determine the trade-off between accuracy, latency, and maintenance cost experimentally. A deeper network does not automatically produce better results.
Is training a model from scratch necessary?
For most applications, a pretrained model can be tried as a starting point. Training from scratch becomes a meaningful alternative only when justified by data volume, domain differences, licensing, and performance requirements.
References and visual provenance
Technical references and original publications are listed below. Photographs used in the visual examples come from real CC0/public-domain examples; transformations made for comparison are explained. The diagrams are original designs. Illustrative examples are not presented as trained-model performance.
Visual sources and illustration note
The photographic examples come from the scikit-image sample data collection. Added boxes, masks, synthetic defects, and heatmaps are illustrations explaining the concepts; they are not outputs from a trained model or validated performance results. The technical diagrams are original drawings included in the package.