Tuesday, January 7, 2025

Designated Initializer in C vs CPP

 C supports a powerful designated initializes specially for Array & Struct in any order. Doesn't depend on declaration order. It was introduced since 1999. Here is an example: 


c example
The output of the above program is:

output

C supports nested, mixed designated initialization: 




C++ initiated this designated initialization in c++20 in year 2020 and we can say it as a limited version. It depends on declaration order of the struct variables. We can not use any order like C language. Also we can not use it for Array :(

Only we can skip some middle variables which will be initialized by zero but we must need to follow it's original declaration order.

Here is an example of c++20:
cpp example

C++ supports mixed type to designated initialization but doesn't support nested type :(




Rules for Designated Initializers (CPP):

1. Each data member can have only one designator.  
2. Designators are applicable only for aggregate initialization.  
3. Nested designators are not allowed.  
4. Regular initialization cannot be combined with designators in the same expression.  
5. It is not mandatory to specify all data members in the initialization expression.  
6. Designators can reference only non-static data members.  
7. The order of designators in the initialization expression must match the order of data members in the class declaration.  

Advantages of Designated Initialization

    Readability: By specifying the exact data member being initialized, the designator ensures clarity and eliminates the possibility of errors.
   Flexibility: It allows you to skip initializing certain data members and depend on their default values instead.
   Compatibility with C: A similar initialization syntax is widely used in C99 (with even more relaxed rules). The C++20 feature enables writing nearly identical code, facilitating code sharing between C and C++.
   Standardization: While compilers like GCC and Clang already provided extensions for this feature, its inclusion in the standard ensures uniform support across all compilers.











Monday, December 30, 2024

Modify a private const variable from outside of class in c++

 Is it possible to modify a private const variable from outside the class in cpp? No it doesn't and it should not supposed to happen.

Unfortunately we can do this with pointer. How? Let's see the example:

#include <iostream>

class Test
{

    private:
    const int cval1 = 1;
    const int cval2 = 2;

    public: 
    void print()
    { 
        std::cout << "const value1 = " << cval1 << std::endl;
        std::cout << "const value2 = " << cval2 << std::endl;

    }    

};

int main()
{

    Test t;
    t.print();

    int * p = reinterpret_cast<int*>(&t);
   *p = 10; //modifying 1st integer
   *(p+1) = 20; //modifying 2nd integer

    std::cout << "After modification: " << std::endl;
    t.print();

    return 0;
}

Tuesday, November 26, 2024

Gender and Age Detection Dataset for Training

Here are some popular datasets you can use for gender and age detection:

1. Adience Dataset

  • Description: Contains images for age and gender estimation. The dataset includes real-world face images with varied poses, occlusions, and lighting conditions.
  • Age Labels: Grouped into ranges like (0-2), (4-6), (8-13), (15-20), etc.
  • Size: ~26,000 face images.
  • Link: Adience Dataset

2. IMDB-WIKI Dataset

  • Description: The largest publicly available dataset for age and gender prediction. It includes face images labeled with age and gender, sourced from IMDb and Wikipedia.
  • Age Labels: Actual age of the individual.
  • Size: ~500,000 face images.
  • Link: IMDB-WIKI Dataset

3. UTKFace Dataset

  • Description: A large-scale dataset with over 20,000 face images labeled for age, gender, and ethnicity. Includes faces of diverse age groups and ethnic backgrounds.
  • Age Labels: Actual age of the individual.
  • Size: ~20,000 face images.
  • Link: UTKFace Dataset

4. FairFace Dataset

  • Description: A balanced dataset for race, age, and gender prediction, designed to mitigate biases in facial analysis systems.
  • Age Labels: Grouped into ranges like 0-2, 3-9, 10-19, etc.
  • Size: ~100,000 images.
  • Link: FairFace Dataset

5. AFAD Dataset

  • Description: Contains over 165,000 images of Asian faces with age and gender labels, focusing on specific demographics.
  • Age Labels: Actual age.
  • Size: ~165,000 images.
  • Link: AFAD Dataset

Best Approach for Gender and Age Detection Training

1. Preprocessing Steps

  • Face Detection: Use a robust face detection model (e.g., Haar cascades, DLIB, MTCNN, or YOLO) to extract face regions.
  • Alignment: Align faces to normalize rotations and scale for consistent inputs.
  • Normalization: Resize face images to a fixed size (e.g., 128x128) and normalize pixel values to [0, 1] or [-1, 1].

2. Model Architecture

  • CNN-Based Models: Convolutional Neural Networks (CNNs) are well-suited for image-based tasks. Popular architectures include:
    • Lightweight models: MobileNet, EfficientNet (good for edge deployment).
    • Deeper models: ResNet, VGG16, or InceptionNet for higher accuracy.
  • Multi-Task Learning (MTL): A shared backbone with separate output layers for gender and age prediction.
    • Example: One softmax layer for gender (Male, Female) and another layer for age regression or classification (age bins).

3. Loss Functions

  • Gender Detection:
    • Use Categorical Cross-Entropy for binary classification (Male, Female).
  • Age Detection:
    • Regression-based: Use Mean Squared Error (MSE) for predicting exact age.
    • Classification-based: Use Categorical Cross-Entropy for age ranges.

4. Training Process

  • Data Augmentation:
    • Random cropping, rotation, horizontal flipping, and brightness adjustments to improve model robustness.
  • Transfer Learning:
    • Start with pre-trained models (e.g., ResNet, MobileNet) on ImageNet and fine-tune for gender and age detection tasks.
  • Balanced Dataset Handling:
    • If classes (e.g., age or gender) are imbalanced, use techniques like oversampling, weighted loss functions, or SMOTE.

5. Evaluation Metrics

  • Gender Detection:
    • Accuracy, Precision, Recall, F1-Score.
  • Age Detection:
    • Mean Absolute Error (MAE) for regression tasks.
    • Accuracy for classification tasks.

6. Advanced Approaches

  • Attention Mechanisms:
    • Use attention layers to focus on key facial features.
  • Ensemble Learning:
    • Combine predictions from multiple models for improved performance.
  • Vision Transformers (ViT):
    • Explore transformers for image-based tasks, especially for large datasets.

Tools and Frameworks:

  • Deep Learning Frameworks: PyTorch, TensorFlow/Keras.
  • Face Detection Libraries: OpenCV, DLIB, MTCNN.

Example Workflow

  1. Prepare Dataset:
    • Download datasets, perform face detection and alignment.
  2. Train the Model:
    • Use transfer learning with pre-trained models like ResNet or EfficientNet.
  3. Evaluate the Model:
    • Test on unseen data and compute metrics.
  4. Deploy the Model:
    • Optimize using ONNX or TensorRT for real-time applications.

By following these steps, you can effectively train a gender and age detection model that performs well even in challenging scenarios.

Adaptive automatic Image enhancing

Adaptive automatic enhancing image for detecting objects. Following cpp opencv code:

 

void AutoEnhanceAdaptivePreprocessing(const cv::Mat& inputImage, cv::Mat& outputImage)
{

// Step 1: Convert to grayscale (if not already)

cv::Mat grayImage;

if (inputImage.channels() == 3)
           cv::cvtColor(inputImage, grayImage, cv::COLOR_BGR2GRAY);

 else
grayImage = inputImage.clone();

//adaptive histogram equalization

// Step 2: Apply CLAHE for adaptive histogram equalization

cv::Ptr<cv::CLAHE> clahe = cv::createCLAHE(2.0, cv::Size(8, 8)); // ClipLimit=2.0, TileGridSize=8x8

cv::Mat claheImage;

clahe->apply(grayImage, claheImage);


// Step 3: Denoising using GaussianBlur

cv::Mat denoisedImage;

cv::GaussianBlur(claheImage, denoisedImage, cv::Size(5, 5), 0);


// Step 4: Enhance contrast and brightness

double alpha = 1.5; // Contrast control (1.0-3.0)

int beta = 20;      // Brightness control (0-100)

cv::Mat contrastEnhancedImage = denoisedImage.clone();

denoisedImage.convertTo(contrastEnhancedImage, -1, alpha, beta);

cv::cvtColor(contrastEnhancedImage, outputImage, cv::COLOR_GRAY2RGB);

}

Wednesday, June 26, 2024

Return Type Overloading in C++

Small tricks to accomplish return type overload in c++. In cpp one can not overload return type. If you follow this trick you can overload return type using operator overloading :)


struct Car {

    string name;

    string brand;

};


struct Bus {

    string name;

    string brand;

};


struct Transport 

{

    Car get_car()

    { 

        Car oCar;

        oCar.name="Axio"; 

        oCar.brand="Toyota";

        return oCar; 

    }

    

    Bus get_bus()

    {

        Bus oBus;

        oBus.name="Greenline"; 

        oBus.brand="Hundai";

        return oBus; 

    }

    

    auto get_transport()

    {

        struct result

        {

          Transport * trans;

          operator Car() { return trans->get_car(); }

          operator Bus() { return trans->get_bus(); }

        };

        

        return (result{this});

    }

};


int main() {

    

    Transport tt;

    Car myCar = tt.get_transport();

    Bus myBus = tt.get_transport();

    

    cout << myCar.name << " == " << myCar.brand << endl;

    cout << myBus.name << " == " << myBus.brand << endl;


    return 0;

}


============

You can not use below code it will get compile error:

struct Transport 

{

    Car get_transport() { return (Car{});}

    Bus get_transport() { return (Bus{});}

};

PC Magazine Tips and Solutions

PC World: Latest Technology News

PCWorld.com - Most Popular Downloads of the Week