β¨ OpenCV Contour Approximation β¨
π In this tutorial, weβll learn about a step-by-step implementation and utilization of OpenCVβs Contour Approximation. When I first chanced upon the concept of Contour Approximation, the first question that hit me was: Why? Throughout my journey in Machine Learning andβ¦...
π·οΈ #ImageProcessing #OpenCVTutorials #Tutorials
π In this tutorial, weβll learn about a step-by-step implementation and utilization of OpenCVβs Contour Approximation. When I first chanced upon the concept of Contour Approximation, the first question that hit me was: Why? Throughout my journey in Machine Learning andβ¦...
π·οΈ #ImageProcessing #OpenCVTutorials #Tutorials
β¨ Image Processing with Gemini Pro β¨
π Table of Contents Image Processing with Gemini Pro Getting Started with Gemini Pro: An Overview Gemini Pro Setup Integrating Google AI Python SDK with Gemini Pro Image Processing with Gemini Pro: Python Code Generation Comprehensive List of GenAI Models Compatibleβ¦...
π·οΈ #ArtificialIntelligence #ChatGPT #DeepLearning #Gemini #GeminiPro #GenAI #GenerativeAI #GoogleCloud #ImageProcessing #Python #Transformers #Tutorial #VertexAI
π Table of Contents Image Processing with Gemini Pro Getting Started with Gemini Pro: An Overview Gemini Pro Setup Integrating Google AI Python SDK with Gemini Pro Image Processing with Gemini Pro: Python Code Generation Comprehensive List of GenAI Models Compatibleβ¦...
π·οΈ #ArtificialIntelligence #ChatGPT #DeepLearning #Gemini #GeminiPro #GenAI #GenerativeAI #GoogleCloud #ImageProcessing #Python #Transformers #Tutorial #VertexAI
β€2
# Real-World Case Study: E-commerce Product Pipeline
import boto3
from PIL import Image
import io
def process_product_image(s3_bucket, s3_key):
# 1. Download from S3
s3 = boto3.client('s3')
response = s3.get_object(Bucket=s3_bucket, Key=s3_key)
img = Image.open(io.BytesIO(response['Body'].read()))
# 2. Standardize dimensions
img = img.convert("RGB")
img = img.resize((1200, 1200), Image.LANCZOS)
# 3. Remove background (simplified)
# In practice: use rembg or AWS Rekognition
img = remove_background(img)
# 4. Generate variants
variants = {
"web": img.resize((800, 800)),
"mobile": img.resize((400, 400)),
"thumbnail": img.resize((100, 100))
}
# 5. Upload to CDN
for name, variant in variants.items():
buffer = io.BytesIO()
variant.save(buffer, "JPEG", quality=95)
s3.upload_fileobj(
buffer,
"cdn-bucket",
f"products/{s3_key.split('/')[-1].split('.')[0]}_{name}.jpg",
ExtraArgs={'ContentType': 'image/jpeg', 'CacheControl': 'max-age=31536000'}
)
# 6. Generate WebP version
webp_buffer = io.BytesIO()
img.save(webp_buffer, "WEBP", quality=85)
s3.upload_fileobj(webp_buffer, "cdn-bucket", f"products/{s3_key.split('/')[-1].split('.')[0]}.webp")
process_product_image("user-uploads", "products/summer_dress.jpg")
By: @DataScienceM π
#Python #ImageProcessing #ComputerVision #Pillow #OpenCV #MachineLearning #CodingInterview #DataScience #Programming #TechJobs #DeveloperTips #AI #DeepLearning #CloudComputing #Docker #BackendDevelopment #SoftwareEngineering #CareerGrowth #TechTips #Python3
β€1
Part 5: Training the Model
We train the model using the
#Training #MachineLearning #ModelFit
---
Part 6: Evaluating and Discussing Results
After training, we evaluate the model's performance on the test set. We also plot the training history to visualize accuracy and loss curves. This helps us understand if the model is overfitting or underfitting.
Discussion:
The plots show how accuracy and loss change over epochs. Ideally, both training and validation accuracy should increase, while losses decrease. If the validation accuracy plateaus or decreases while training accuracy continues to rise, it's a sign of overfitting. Our simple model achieves a decent accuracy. To improve it, one could use techniques like Data Augmentation, Dropout layers, or a deeper architecture.
#Evaluation #Results #Accuracy #Overfitting
---
Part 7: Making Predictions on a Single Image
This is how you handle a single image file for prediction. The model expects a batch of images as input, so we must add an extra dimension to our single image before passing it to
#Prediction #ImageProcessing #Inference
βββββββββββββββ
By: @DataScienceM β¨
We train the model using the
fit() method, providing our training data, batch size, number of epochs, and validation data to monitor performance on unseen data.history = model.fit(x_train, y_train,
epochs=15,
batch_size=64,
validation_data=(x_test, y_test))
#Training #MachineLearning #ModelFit
---
Part 6: Evaluating and Discussing Results
After training, we evaluate the model's performance on the test set. We also plot the training history to visualize accuracy and loss curves. This helps us understand if the model is overfitting or underfitting.
# Evaluate the model on the test data
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print(f'\nTest accuracy: {test_acc:.4f}')
# Plot training & validation accuracy values
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
# Plot training & validation loss values
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
Discussion:
The plots show how accuracy and loss change over epochs. Ideally, both training and validation accuracy should increase, while losses decrease. If the validation accuracy plateaus or decreases while training accuracy continues to rise, it's a sign of overfitting. Our simple model achieves a decent accuracy. To improve it, one could use techniques like Data Augmentation, Dropout layers, or a deeper architecture.
#Evaluation #Results #Accuracy #Overfitting
---
Part 7: Making Predictions on a Single Image
This is how you handle a single image file for prediction. The model expects a batch of images as input, so we must add an extra dimension to our single image before passing it to
model.predict().# Select a single image from the test set
img_index = 15
test_image = x_test[img_index]
true_label_index = np.argmax(y_test[img_index])
# Display the image
plt.imshow(test_image)
plt.title(f"Actual Label: {class_names[true_label_index]}")
plt.show()
# The model expects a batch of images, so we add a dimension
image_for_prediction = np.expand_dims(test_image, axis=0)
print("Image shape before prediction:", test_image.shape)
print("Image shape after adding batch dimension:", image_for_prediction.shape)
# Make a prediction
predictions = model.predict(image_for_prediction)
predicted_label_index = np.argmax(predictions[0])
# Print the result
print(f"\nPrediction Probabilities: {predictions[0]}")
print(f"Predicted Label: {class_names[predicted_label_index]}")
print(f"Actual Label: {class_names[true_label_index]}")
#Prediction #ImageProcessing #Inference
βββββββββββββββ
By: @DataScienceM β¨
Please open Telegram to view this post
VIEW IN TELEGRAM
Top 30 MATLAB Image Processing Functions
#MATLAB #ImageProcessing #Basics
#1.
Reads an image from a file into a matrix.
#2.
Displays an image in a figure window.
#3.
Writes an image matrix to a file.
#4.
Returns the dimensions of the image matrix (rows, columns, color channels).
#5.
Converts an RGB color image to a grayscale intensity image.
---
#MATLAB #ImageProcessing #Conversion #Transformation
#6.
Converts an image to double-precision format, scaling data to the range [0, 1].
#7.
Resizes an image to a specified size.
#8.
Rotates an image by a specified angle.
#9.
Crops an image to a specified rectangle.
#10.
Converts an RGB image to the Hue-Saturation-Value (HSV) color space.
---
#MATLAB #ImageProcessing #Enhancement
#11.
Displays the histogram of an image, showing the distribution of pixel intensity values.
#MATLAB #ImageProcessing #Basics
#1.
imread()Reads an image from a file into a matrix.
img = imread('peppers.png');
disp('Image "peppers.png" loaded into variable "img".');Image "peppers.png" loaded into variable "img".
#2.
imshow()Displays an image in a figure window.
img = imread('peppers.png');
imshow(img);
title('Peppers Image');Output: A new figure window opens, displaying the 'peppers.png' image with the title "Peppers Image".
#3.
imwrite()Writes an image matrix to a file.
img = imread('cameraman.tif');
imwrite(img, 'my_cameraman.jpg');
disp('Image saved as my_cameraman.jpg');Image saved as my_cameraman.jpg
#4.
size()Returns the dimensions of the image matrix (rows, columns, color channels).
rgb_img = imread('peppers.png');
gray_img = imread('cameraman.tif');
size_rgb = size(rgb_img);
size_gray = size(gray_img);
disp(['Size of RGB image: ', num2str(size_rgb)]);
disp(['Size of grayscale image: ', num2str(size_gray)]);Size of RGB image: 384 512 3
Size of grayscale image: 256 256
#5.
rgb2gray()Converts an RGB color image to a grayscale intensity image.
rgb_img = imread('peppers.png');
gray_img = rgb2gray(rgb_img);
imshow(gray_img);
title('Grayscale Peppers');Output: A figure window displays the grayscale version of the peppers image.
---
#MATLAB #ImageProcessing #Conversion #Transformation
#6.
im2double()Converts an image to double-precision format, scaling data to the range [0, 1].
img_uint8 = imread('cameraman.tif');
img_double = im2double(img_uint8);
disp(['Max value of original image: ', num2str(max(img_uint8(:)))]);
disp(['Max value of double image: ', num2str(max(img_double(:)))]);Max value of original image: 253
Max value of double image: 0.99216
#7.
imresize()Resizes an image to a specified size.
img = imread('cameraman.tif');
resized_img = imresize(img, 0.5); % Resize to 50% of original size
imshow(resized_img);
title('Resized Cameraman');Output: A figure window displays the cameraman image at half its original size.
#8.
imrotate()Rotates an image by a specified angle.
img = imread('cameraman.tif');
rotated_img = imrotate(img, 30, 'bilinear', 'crop');
imshow(rotated_img);
title('Rotated 30 Degrees');Output: A figure window displays the cameraman image rotated by 30 degrees, cropped to the original size.
#9.
imcrop()Crops an image to a specified rectangle.
img = imread('peppers.png');
% [xmin ymin width height]
cropped_img = imcrop(img, [100 80 250 200]);
imshow(cropped_img);
title('Cropped Image');Output: A figure window displays only the rectangular section specified from the peppers image.
#10.
rgb2hsv()Converts an RGB image to the Hue-Saturation-Value (HSV) color space.
rgb_img = imread('peppers.png');
hsv_img = rgb2hsv(rgb_img);
hue_channel = hsv_img(:,:,1); % Extract the Hue channel
imshow(hue_channel);
title('Hue Channel of Peppers Image');Output: A figure window displays the Hue channel of the peppers image as a grayscale image.
---
#MATLAB #ImageProcessing #Enhancement
#11.
imhist()Displays the histogram of an image, showing the distribution of pixel intensity values.
gray_img = imread('pout.tif');
imhist(gray_img);
title('Histogram of a Low-Contrast Image');Output: A figure window with a bar chart showing the intensity distribution of the 'pout.tif' image.
#12.
histeq()Enhances contrast using histogram equalization.
low_contrast_img = imread('pout.tif');
high_contrast_img = histeq(low_contrast_img);
imshow(high_contrast_img);
title('Histogram Equalized Image');Output: A figure window displays a higher contrast version of the 'pout.tif' image.
#13.
imadjust()Adjusts image intensity values or colormap by mapping intensity values to new values.
img = imread('cameraman.tif');
adjusted_img = imadjust(img, [0.3 0.7], []);
imshow(adjusted_img);
title('Intensity Adjusted Image');Output: A figure window showing a high-contrast version of the cameraman image, where intensities between 0.3 and 0.7 are stretched to the full [0, 1] range.
#14.
imtranslate()Translates (shifts) an image horizontally and vertically.
img = imread('cameraman.tif');
translated_img = imtranslate(img, [25, 15]); % Shift 25 pixels right, 15 pixels down
imshow(translated_img);
title('Translated Image');Output: A figure window shows the cameraman image shifted to the right and down.
#15.
imsharpen()Sharpens an image using the unsharp masking method.
img = imread('peppers.png');
sharpened_img = imsharpen(img);
imshow(sharpened_img);
title('Sharpened Image');Output: A figure window displays a crisper, more detailed version of the peppers image.
---
#MATLAB #ImageProcessing #Filtering #Noise
#16.
imnoise()Adds a specified type of noise to an image.
img = imread('cameraman.tif');
noisy_img = imnoise(img, 'salt & pepper', 0.02);
imshow(noisy_img);
title('Image with Salt & Pepper Noise');Output: A figure window displays the cameraman image with random white and black pixels (noise).
#17.
fspecial()Creates a predefined 2-D filter kernel (e.g., for averaging, Gaussian blur, Laplacian).
h = fspecial('motion', 20, 45); % Create a motion blur filter
disp('Generated a 2D motion filter kernel.');
disp(h);Generated a 2D motion filter kernel.
(Output is a matrix representing the filter kernel)
#18.
imfilter()Filters a multidimensional image with a specified filter kernel.
img = imread('cameraman.tif');
h = fspecial('motion', 20, 45);
motion_blur_img = imfilter(img, h, 'replicate');
imshow(motion_blur_img);
title('Motion Blurred Image');Output: A figure window shows the cameraman image with a motion blur effect applied at a 45-degree angle.
#19.
medfilt2()Performs 2-D median filtering, which is excellent for removing 'salt & pepper' noise.
noisy_img = imnoise(imread('cameraman.tif'), 'salt & pepper', 0.02);
denoised_img = medfilt2(noisy_img);
imshow(denoised_img);
title('Denoised with Median Filter');Output: A figure window shows the noisy image significantly cleaned up, with most salt & pepper noise removed.
#20.
edge()Finds edges in an intensity image using various algorithms (e.g., Sobel, Canny).
img = imread('cameraman.tif');
edges = edge(img, 'Canny');
imshow(edges);
title('Edges found with Canny Detector');Output: A figure window displays a binary image showing only the detected edges from the original image in white.
---
#MATLAB #ImageProcessing #Segmentation #Morphology
#21.
graythresh()Computes a global image threshold from a grayscale image using Otsu's method.
img = imread('coins.png');
level = graythresh(img);
disp(['Optimal threshold level (Otsu): ', num2str(level)]);Optimal threshold level (Otsu): 0.49412
#22.
imbinarize()Converts a grayscale image to a binary image based on a threshold.
img = imread('coins.png');
level = graythresh(img); % Find optimal threshold
bw_img = imbinarize(img, level);
imshow(bw_img);
title('Binarized Image (Otsu Method)');Output: A figure window displays a black and white image of the coins.
#23.
strel()Creates a morphological structuring element (SE), which is used to probe an image in morphological operations.
se = strel('disk', 5);
disp('Created a disk-shaped structuring element with radius 5.');
disp(se);Created a disk-shaped structuring element with radius 5.
(Output describes the strel object and shows its matrix representation)
#24.
imdilate()Dilates a binary image, making objects larger and filling small holes.
img = imread('text.png');
se = strel('line', 3, 90); % A vertical line SE
dilated_img = imdilate(img, se);
imshow(dilated_img);
title('Dilated Text');Output: A figure window shows the text characters appearing thicker, especially in the vertical direction.
#25.
imerode()Erodes a binary image, shrinking objects and removing small noise.
img = imread('text.png');
se = strel('line', 3, 0); % A horizontal line SE
eroded_img = imerode(img, se);
imshow(eroded_img);
title('Eroded Text');Output: A figure window shows the text characters appearing thinner, with horizontal parts possibly disappearing.
---
#MATLAB #ImageProcessing #Analysis
#26.
imopen()Performs morphological opening (erosion followed by dilation). It smooths contours and removes small objects.
original = imread('circbw.tif');
se = strel('disk', 10);
opened_img = imopen(original, se);
imshow(opened_img);
title('Morphologically Opened Image');Output: A figure window displays the image with small protrusions removed and gaps between objects widened.
#27.
bwareaopen()Removes all connected components (objects) from a binary image that have fewer than a specified number of pixels.
img = imread('text.png');
cleaned_img = bwareaopen(img, 50); % Remove objects with fewer than 50 pixels
imshow(cleaned_img);
title('Image after removing small objects');Output: A figure window shows the text image with small noise specks or broken parts of characters removed.
#28.
bwlabel()Labels connected components in a binary image.
img = imread('text.png');
[L, num] = bwlabel(img);
disp(['Number of connected objects found: ', num2str(num)]);Number of connected objects found: 114
#29.
regionprops()Measures a set of properties for each labeled region in an image.