Archive

Posts Tagged ‘technology’

C# – using #OpenCV to determine if an image contains an image of a car (or a duck)

TL;DR; Here is the repo: https://github.com/infiniteloopltd/IsItACar

This demo application can take an image and derermine if the image is that of a Car, or not a car. My test image was of a duck, which was very defintely not car-like. But sillyness aside, this can be very useful for image upload validation – if you want to ensure that your car-sales website doesn’t allow their users to upload nonsense pictures, but only of cars, then this code could be useful.

Why Use Emgu.CV for Computer Vision?

Emgu.CV simplifies the use of OpenCV in C# projects, providing an intuitive interface while keeping the full functionality of OpenCV. For tasks like object detection, it is an ideal choice due to its performance and flexibility.


Prerequisites

Before diving into the code, make sure you have the following set up:

  • Visual Studio (or another preferred C# development environment)
  • Emgu.CV library installed via NuGet:
    • Search for Emgu.CV and Emgu.CV.runtime.windows in the NuGet Package Manager and install them.

Setting Up Your Project

We’ll write a simple application to detect cars in an image. The code uses a pre-trained Haar cascade classifier, which is a popular method for object detection.

The Code

Here’s a complete example demonstrating how to load an image from a byte array and run car detection using Emgu.CV:

csharpCopy codeusing Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using System;
using System.Drawing;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        // Load the image into a byte array (this could come from a database or API)
        byte[] imageBytes = File.ReadAllBytes("path_to_your_image.jpg");

        // Create a Mat object to hold the decoded image
        Mat mat = new Mat();

        // Decode the image from the byte array into the Mat object
        CvInvoke.Imdecode(imageBytes, ImreadModes.Color, mat);

        // Convert the Mat to an Image<Bgr, byte> for further processing
        Image<Bgr, byte> image = mat.ToImage<Bgr, byte>();

        // Load the Haar cascade for car detection
        string cascadeFilePath = "path_to_haarcascade_car.xml"; // Download a Haar cascade for cars
        CascadeClassifier carClassifier = new CascadeClassifier(cascadeFilePath);

        // Convert to grayscale for better detection performance
        using (var grayImage = image.Convert<Gray, byte>())
        {
            // Detect cars in the image
            Rectangle[] cars = carClassifier.DetectMultiScale(
                grayImage, 
                scaleFactor: 1.1, 
                minNeighbors: 5, 
                minSize: new Size(30, 30));

            // Draw rectangles around detected cars
            foreach (var car in cars)
            {
                image.Draw(car, new Bgr(Color.Red), 2);
            }

            // Save or display the image with the detected cars
            image.Save("output_image_with_cars.jpg");
            Console.WriteLine($"Detected {cars.Length} car(s) in the image.");
        }
    }
}

Breaking Down the Code

  1. Loading the Image as a Byte Array:csharpCopy codebyte[] imageBytes = File.ReadAllBytes("path_to_your_image.jpg"); Instead of loading an image from a file directly, we load it into a byte array. This approach is beneficial if your image data is not file-based but comes from a more dynamic source, such as a database.
  2. Decoding the Image:csharpCopy codeMat mat = new Mat(); CvInvoke.Imdecode(imageBytes, ImreadModes.Color, mat); We use CvInvoke.Imdecode to convert the byte array into a Mat object, which is OpenCV’s matrix representation of images.
  3. Converting Mat to Image<Bgr, byte>:csharpCopy codeImage<Bgr, byte> image = mat.ToImage<Bgr, byte>(); The Mat is converted to Image<Bgr, byte> to make it easier to work with Emgu.CV functions.
  4. Car Detection Using Haar Cascades:csharpCopy codeRectangle[] cars = carClassifier.DetectMultiScale(grayImage, 1.1, 5, new Size(30, 30)); The Haar cascade method is used for object detection. You’ll need to download a Haar cascade XML file for cars and provide the path.
  5. Drawing Detected Cars:csharpCopy codeimage.Draw(car, new Bgr(Color.Red), 2); Rectangles are drawn around detected cars, and the image is saved or displayed.

Downloading Haar Cascade for Cars

To detect cars, you need a pre-trained Haar cascade file. You can find these files on the OpenCV GitHub repository or by searching online for “haarcascade for car detection.”


Conclusion

This example demonstrates a simple yet powerful way to use Emgu.CV for car detection in C#. While Haar cascades are efficient, modern machine learning methods like YOLO or SSD are more accurate for complex tasks. However, for basic object detection, this approach is easy to implement and performs well for simpler use cases.

Feel free to experiment with different parameters to improve detection accuracy or try integrating more advanced models for more complex scenarios. Happy coding!

#AWS #S3 Error – The request signature we calculated does not match the signature you provided. Check your key and signing method

If you’re working with the AWS SDK for .NET and encounter an error when uploading files to an Amazon S3 bucket, you’re not alone. A recent upgrade in the SDK may introduce unexpected behavior, leading to a “signature mismatch” error for uploads that previously worked smoothly. This blog post describes the problem, analyzes common solutions, and explains how AWS S3 pathing conventions have changed over time—impacting how we specify folders within S3 buckets.

The Problem: “The request signature we calculated does not match the signature you provided.”

When uploading a file to an Amazon S3 bucket using a .NET application, you may encounter this error:

“The request signature we calculated does not match the signature you provided. Check your key and signing method.”

The symptoms of this error can be puzzling. For example, a standard upload to the root of the bucket may succeed, but attempting to upload to a specific folder within the bucket could trigger the error. This was the case in a recent project, where an upload to the bucket carimagerydata succeeded, while uploads to carimagerydata/tx returned the signature mismatch error. The access key, secret key, and permissions were all configured correctly, but specifying the folder path still caused a failure.

Possible Solutions

When you encounter this issue, there are several things to investigate:

1. Bucket Region Configuration

Ensure that the AWS SDK is configured with the correct region for the S3 bucket. The SDK signs requests based on the region setting, and a mismatch between the region used in the code and the actual bucket region often results in signature errors.

csharpCopy codeAmazonS3Config config = new AmazonS3Config
{
    RegionEndpoint = RegionEndpoint.YourBucketRegion // Ensure it's correct
};

2. Signature Version Settings

The AWS SDK uses Signature Version 4 by default, which is compatible with most regions and recommended by AWS. However, certain legacy setups or bucket configurations may expect Signature Version 2. Explicitly setting Signature Version 4 in the configuration can sometimes resolve these errors.

csharpCopy codeAmazonS3Config config = new AmazonS3Config
{
    SignatureVersion = "4", // Explicitly specify Signature Version 4
    RegionEndpoint = RegionEndpoint.YourBucketRegion
};

3. Permissions and Bucket Policies

Check if there are any bucket policies or IAM restrictions specific to the folder path you’re trying to upload to. If your bucket policy restricts access to certain paths, you’ll need to adjust it to allow uploads to the folder.

4. Path Style vs. Virtual-Hosted Style URL

Another possible issue arises from changes in how paths are handled. The AWS SDK has evolved over time, and the method of specifying paths within buckets has also changed. The SDK now defaults to virtual-hosted style URLs, where the bucket name is part of the domain (e.g., bucket-name.s3.amazonaws.com). Older setups, however, may expect path-style URLs, where the bucket name is part of the path (e.g., s3.amazonaws.com/bucket-name/key). Specifying path-style addressing in the configuration can sometimes fix compatibility issues:

csharpCopy codeAmazonS3Config config = new AmazonS3Config
{
    UsePathStyle = true,
    RegionEndpoint = RegionEndpoint.YourBucketRegion
};

Understanding the Key Change: Folder Path Format in S3

The reason these issues are so confusing is that AWS has changed the way folders (often called prefixes) are specified. Historically, users specified a bucket name combined with a folder path and then provided the object’s name. Now, however, the SDK expects a more unified format:

  • Old Format: bucket + path, object
  • New Format: bucket, path + object

This means that in the new format, the folder path (e.g., /tx/) should be included as part of the object key rather than being treated as a separate parameter.

Solution: Specifying the Folder in the Object Key

To upload to a folder within a bucket, you should include the full path in the key itself. For example, if you want to upload yourfile.txt to the tx folder within carimagerydata, the key should be specified as "tx/yourfile.txt".

Here’s how to do it in C#:

csharpCopy codestring bucketName = "carimagerydata";
string keyName = "tx/yourfile.txt"; // Specify the folder in the key
string filePath = @"C:\path\to\your\file.txt";

AmazonS3Client client = new AmazonS3Client(accessKey, secretKey, RegionEndpoint.YourBucketRegion);

PutObjectRequest request = new PutObjectRequest
{
    BucketName = bucketName,
    Key = keyName, // Full path including folder
    FilePath = filePath,
    ContentType = "text/plain" // Example for text files, adjust as needed
};

PutObjectResponse response = await client.PutObjectAsync(request);

Conclusion

This error is a prime example of how changes in SDK conventions can impact legacy applications. The update to a more unified key format for specifying folder paths in S3 may seem minor, but it can cause unexpected issues if you’re unaware of it. By specifying the folder as part of the object key, you can avoid signature mismatch errors and ensure that your application is compatible with the latest AWS SDK practices.

Always remember to check SDK release notes for updates in configuration defaults, particularly when working with cloud services, as conventions and standards may change over time. This small adjustment can save a lot of time when troubleshooting!

Categories: Uncategorized Tags: , , , ,

Car License Plate #API support for #Lithuania

Introducing support for Lithuania via our Car License Plate API

Are you looking to seamlessly integrate detailed vehicle information into your applications? Welcome to Numerio Zenklai API, Lithuania’s latest and most advanced car license plate API. This service is designed to provide comprehensive vehicle details, enhancing your ability to offer top-tier services in the automotive, insurance, and related industries.

Why Choose Numerio Zenklai API?

Numerio Zenklai API offers a robust solution for retrieving detailed information about vehicles registered in Lithuania. With a simple request to the /CheckLithuania endpoint, you can obtain critical data, including the vehicle’s make, model, age, engine size, VIN, insurer, and a representative image.

Key Features

1. Comprehensive Vehicle Data:
Access a rich set of details about any Lithuanian-registered vehicle. For example, a query on the registration number “NAO075” returns the following data:

  • Make and Model: Volkswagen Crafter
  • Registration Year: 2006
  • Engine Size: 2461 cc
  • VIN: WV1ZZZ2EZE6017394
  • Fuel Type: Diesel
  • Insurance Company: ERGO INSURANCE SE LIETUVOS FILIALAS
  • Vehicle Type: Lorry
  • Body Type: Bus
  • Representative Image: Image URL

2. Simple and Fast Integration:
Our API is designed for quick integration, ensuring you can start leveraging vehicle data with minimal setup. Here’s a sample JSON response for an easy understanding of the data format:

{
"Description": "VOLKSWAGEN CRAFTER",
"RegistrationYear": "2006",
"CarMake": {
"CurrentTextValue": "VOLKSWAGEN"
},
"CarModel": {
"CurrentTextValue": "CRAFTER"
},
"MakeDescription": {
"CurrentTextValue": "VOLKSWAGEN"
},
"ModelDescription": {
"CurrentTextValue": "CRAFTER"
},
"EngineSize": {
"CurrentTextValue": "2461"
},
"VIN": "WV1ZZZ2EZE6017394",
"FuelType": "Diesel",
"InsuranceCompany": "ERGO INSURANCE SE LIETUVOS FILIALAS",
"InsuranceCompanyNumber": "ACB 1798038:8192689",
"VehicleType": "LORRY",
"Body": "Bus",
"ImageUrl": "http://www.numeriozenklaiapi.lt/image.aspx/@Vk9MS1NXQUdFTiBDUkFGVEVS"
}

3. Reliable and Up-to-Date Information:
Our API ensures that you always receive the most current and accurate data directly from official sources, making it a reliable tool for various applications.

Use Cases

  • Automotive Industry: Quickly verify vehicle details for sales, maintenance, and servicing.
  • Insurance Companies: Validate vehicle information for underwriting and claims processing.
  • Fleet Management: Monitor and manage a fleet of vehicles efficiently with detailed data.
  • Law Enforcement: Access critical vehicle information swiftly for enforcement and regulatory purposes.

Getting Started

To begin using Numerio Zenklai API, visit our website and check out our comprehensive documentation. Our user-friendly interface and extensive support resources make it easy for developers to integrate the API into their existing systems.

Conclusion

Numerio Zenklai API is your go-to solution for accessing detailed vehicle information in Lithuania. Whether you’re in the automotive industry, insurance sector, or any field that requires precise vehicle data, our API provides the tools you need to enhance your services and streamline your operations.

Experience the power of reliable vehicle information with Numerio Zenklai API today. Visit Numerio Zenklai API to learn more and start integrating now!

Car Registration #API now available in #Switzerland


Introducing KennzeichenAPI:
Your Ultimate Swiss License Plate Lookup Tool

Whether you’re a curious car enthusiast, an insurance agent, or law enforcement personnel, having access to accurate and comprehensive vehicle information can be invaluable. Enter KennzeichenAPI, a groundbreaking new tool that brings clarity to the world of Swiss car registration plates.

Understanding Swiss License Plates

Switzerland boasts a unique system for car registration plates, each carrying a wealth of information about the vehicle it belongs to. From the make and model to technical specifications and even representative images, Swiss license plates hold the key to unlocking a vehicle’s history and characteristics.

Introducing KennzeichenAPI

KennzeichenAPI is a powerful API (Application Programming Interface) designed specifically to decode Swiss license plates effortlessly. With its user-friendly interface and robust functionality, KennzeichenAPI offers a seamless solution for retrieving detailed information about vehicles registered in Switzerland.

Features

1. Make and Model

Get instant access to the make and model of a vehicle, providing valuable insights into its brand and design.

2. Age

Discover the registration year and month of the vehicle, shedding light on its age and potentially its usage history.

3. Transmission and Fuel Type

Learn about the transmission system and fuel type of the vehicle, crucial details for both enthusiasts and professionals alike.

4. Doors and Body

Understand the number of doors and the body type of the vehicle, offering a glimpse into its structural design.

5. Engine Type and Size

Explore the engine specifications, including type and size, essential for evaluating performance and efficiency.

6. Euro Type Code

Access information about the Euro Type Code, providing insights into the vehicle’s compliance with European emissions standards.

7. Representative Image

Visualize the vehicle with a representative image, enhancing the overall user experience and facilitating identification.

How It Works

Using KennzeichenAPI is simple and straightforward. With just a license plate number, users can query the API and receive a JSON response containing all relevant information about the corresponding vehicle. Let’s take a look at a sample response:

jsonCopy code{
  "Description": "Honda CR-Z",
  "Variant": "CR-Z 1.5i Hybrid GT Coupé - 3 doors - 114 HP - Manuell - 35100 Fr.",
  "RegistrationYear": 2012,
  "RegistrationMonth": 9,
  "CarMake": {
    "CurrentTextValue": "Honda"
  },
  "CarModel": {
    "CurrentTextValue": "CR-Z"
  },
  "Transmission": "Manual",
  "EngineSize": "1497",
  "Power": "84",
  "FuelType": "Benzin / Elektrisch",
  "Doors": "0",
  "Body": "Limousine",
  "EngineType": "LEA1",
  "TypeCertificate": "1HA341",
  "EuroTypeCode": "e11*2007/46-79/2009*0100",
  "Co2": "117",
  "Region": "Aargau",
  "ImageUrl": "http://kennzeichenapi.ch/image.aspx/@SG9uZGEgQ1ItWg=="
}

Example Usage

Let’s say you come across a Swiss license plate with the registration number “AG364769.” By making a simple API call to the /CheckSwitzerland endpoint with this license plate number, you can retrieve comprehensive information about the corresponding vehicle, including its make, model, age, transmission, fuel type, and much more.

import requests

license_plate = "AG364769"
api_url = f"https://www.kennzeichenapi.ch/api/reg.asmx/CheckSwitzerland?licensePlate={license_plate}"

response = requests.get(api_url)
data = response.json()

print(data)

With KennzeichenAPI, unlocking the mysteries behind Swiss license plates has never been easier. Whether you’re conducting research, verifying vehicle details, or satisfying your curiosity, KennzeichenAPI empowers you with the information you need, right when you need it.

Get Started Today!

Ready to explore the world of Swiss license plates like never before? Visit KennzeichenAPI today and start harnessing the power of comprehensive vehicle information at your fingertips. Unlock the potential of Swiss license plates with KennzeichenAPI – your ultimate license plate lookup tool!