Shape Detection
TensorFlow
Machine Learning
Computer Vision
Deep Learning

shape Detection - TensorFlow

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

For simple geometric shape detection in TensorFlow 1, the most practical approach is usually image classification rather than general object detection. If each image contains one main shape such as a circle, square, or triangle, a small convolutional neural network can classify the image accurately without the complexity of a full detection pipeline.

Frame the Problem Correctly

The title says “shape detection”, but there are really two different problems:

  • classify the whole image as one shape
  • locate shapes inside a larger scene

TensorFlow 1 can do either, but they are very different workloads. For a first implementation, start with classification unless you genuinely need bounding boxes.

Build a Simple TensorFlow 1 Classifier

The example below uses placeholders and sessions in classic TensorFlow 1 style:

python
1import tensorflow as tf
2
3tf.compat.v1.disable_eager_execution()
4
5x = tf.compat.v1.placeholder(tf.float32, shape=[None, 64, 64, 1], name="x")
6y = tf.compat.v1.placeholder(tf.float32, shape=[None, 3], name="y")
7
8conv1 = tf.compat.v1.layers.conv2d(x, filters=16, kernel_size=3, activation=tf.nn.relu)
9pool1 = tf.compat.v1.layers.max_pooling2d(conv1, pool_size=2, strides=2)
10
11conv2 = tf.compat.v1.layers.conv2d(pool1, filters=32, kernel_size=3, activation=tf.nn.relu)
12pool2 = tf.compat.v1.layers.max_pooling2d(conv2, pool_size=2, strides=2)
13
14flat = tf.compat.v1.layers.flatten(pool2)
15dense = tf.compat.v1.layers.dense(flat, 64, activation=tf.nn.relu)
16logits = tf.compat.v1.layers.dense(dense, 3)
17
18loss = tf.reduce_mean(
19    tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=logits)
20)
21
22train_op = tf.compat.v1.train.AdamOptimizer(1e-3).minimize(loss)
23predictions = tf.argmax(logits, axis=1)

Here the three output classes might be circle, square, and triangle.

Preprocess the Images Consistently

For simple shapes, preprocessing matters almost as much as model size:

  • convert images to grayscale
  • resize to a fixed size such as 64 x 64
  • normalize pixel values to [0, 1]
  • keep labels consistent

If the training set mixes different sizes, backgrounds, and stroke widths without any consistency, the model may learn the wrong patterns.

A minimal NumPy preprocessing step might look like:

python
1import cv2
2import numpy as np
3
4def load_image(path):
5    image = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
6    image = cv2.resize(image, (64, 64))
7    image = image.astype(np.float32) / 255.0
8    return image.reshape(64, 64, 1)

That is enough for many small synthetic shape datasets.

Train with a Session

TensorFlow 1 training still revolves around sessions:

python
1with tf.compat.v1.Session() as sess:
2    sess.run(tf.compat.v1.global_variables_initializer())
3
4    for epoch in range(10):
5        _, current_loss = sess.run(
6            [train_op, loss],
7            feed_dict={
8                x: x_batch,
9                y: y_batch,
10            },
11        )
12        print("epoch", epoch, "loss", current_loss)

The code assumes you already prepared x_batch and y_batch. In a real project, those would come from your dataset pipeline.

If You Need Actual Detection

If your images contain multiple shapes or shapes at unknown locations, classification is no longer enough. Then you need:

  • bounding-box labels
  • a detection model
  • post-processing for detected regions

That is a significantly bigger project. Many developers jump straight to detection when a simple classifier would have solved their real use case with far less effort.

For classroom or prototype projects, shape datasets are often synthetic. That is fine, but remember that perfectly clean generated shapes do not represent the messiness of real camera images. If deployment images contain shadows, rotation, perspective, or cluttered backgrounds, include those conditions in training and validation instead of assuming a toy dataset proves general robustness.

Common Pitfalls

  • Treating a classification problem as object detection before confirming the requirements.
  • Training on inconsistent image sizes, backgrounds, or labels.
  • Expecting TensorFlow 1 placeholder code to behave like modern eager-execution TensorFlow.
  • Using too little data and then blaming the architecture for poor accuracy.
  • Forgetting that the model learns from training examples, not from geometric definitions of circles or squares.

Summary

  • For simple shape recognition, start with image classification rather than full detection.
  • In TensorFlow 1, use placeholders, layers, and sessions in the classic graph-execution style.
  • Normalize images consistently before training.
  • A small CNN is often enough for circles, squares, and triangles on clean datasets.
  • Move to real detection only when you actually need localization, not just class labels.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.