How to crop image based on Azure object detection output - azure

I've an MS Azure Object detection model in customvision.ai website. I make predictions using it's API, then draw output bounding box as rectangle in the image. Following is the powershell code to achieve that:
#First powershell script
#API call to object detection model to predict objects and their bounding boxes
$filePath = "C:\ImageOne.jpg"
$fileBytes = [System.IO.File]::ReadAllBytes($FilePath);
$Url = "<MyCustomVisionModelEndpoint>"
$headers = #{
'Prediction-Key' = $customVisionPredictionKey
'Content-Type' = 'application/octet-stream'
}
$proxy = [System.Net.WebRequest]::GetSystemWebProxy().GetProxy("https://<CustomVisionResourceName>.cognitiveservices.azure.com")
$APIresult = Invoke-RestMethod -Method 'Post' -Uri $url -Body $fileBytes -Headers $headers -UseDefaultCredentials -Proxy $proxy -ProxyUseDefaultCredentials
#Get Results and draw the predicted bounding boxes in the input image
$results = $APIresult.predictions | Where-Object {!$_.tagName.toString().contains("not") -and !$_.tagName.toString().contains("door") -and !$_.tagName.toString().contains("tyre") -and $_.probability -ge 0.02}
Add-Type -AssemblyName System.Drawing
$srcImage=[System.Drawing.Image]::FromFile($FilePath)
$height = $srcImage.height
$width = $srcImage.width
$graphics=[System.Drawing.Graphics]::FromImage($srcImage)
$pen = New-Object Drawing.Pen([System.Drawing.Color]::Blue,3);
$font = New-Object Drawing.Font("Arial", 7);
$brush = New-Object Drawing.SolidBrush([System.Drawing.Color]::Red);
foreach($result in $results)
{
$left = $width * $result.boundingBox.left
$top = $height * $result.boundingBox.top
$PHeight = $height * $result.boundingBox.height
$PWidth = $width * $result.boundingBox.width
$rect = New-Object Drawing.Rectangle($left, $top, $PWidth, $PHeight);
$graphics.DrawRectangle($pen, $rect);
$tag = "Tag: " + $result.tagName + " ,Probability: " + [math]::Round($result.probability * 100,2)
$graphics.DrawString($tag,$font,$brush,$left, $top);
}
$graphics.Dispose()
if($results)
{
$srcImage.Save("D:\Output.jpg")
}
Assume that my object detection model predicted one object. Now I want to use this predicted object bounding boxes and crop the original image with these boudning box co-ordinates. Following is the powershell code to achieve that:
#Second powershell script
Add-Type -AssemblyName System.Drawing
$filepath = "C:\ImageOne.jpg"
$srcImage=[System.Drawing.Image]::FromFile($FilePath)
$srcRect = New-Object Drawing.Rectangle(0,0,$srcImage.Width,$srcImage.Height)
#Here left, top, width, height co-ordinates comes from above powershell code which does predictions and draws rectangular bounding boxes
$destRect = New-Object Drawing.Rectangle([UInt32]($left),[UInt32]($top),[UInt32]($PWidth),[UInt32]($PHeight))
$bmp=new-object System.Drawing.Bitmap($destRect.Width,$destRect.Height)
$graphics=[System.Drawing.Graphics]::FromImage($bmp)
#I tried with [System.Drawing.GraphicsUnit]::Pixel also, but no use
$units = [System.Drawing.GraphicsUnit]::Point
$destRect = new-object Drawing.Rectangle($destRect.Left, $destRect.Top, $destRect.Width, $destRect.Height)
$srcRect = new-object Drawing.Rectangle($srcRect.Left, $srcRect.Top, $srcRect.Width, $srcRect.Height)
$graphics.DrawImage($srcImage, $srcRect, $destRect, $units)
$graphics.Dispose()
$bmp.Save("D:\test.jpg")
I prepared second powershell script with the help of this link:
Powershell use .NET .DrawImage in System.Drawing
The first code is working fine, I'm able to do predictions, draw predicted objects bounding box in the input image.
I'm using same predicted bounding box co-ordinates in the second script and trying to crop that predicted object area. But it's not cropping correctly.
The first script drew bounding box correctly, but second script is cropping some other part of the image.
I assume there might be some mistake in second powershell script. I'm not able to understand what's going wrong. Can someone please help me?

In the second powershell script, I changed the bitmap as follows:
$bmp=new-object System.Drawing.Bitmap($srcImage.Width,$srcImage.Height)
Then I changed graphics unit to
[System.Drawing.GraphicsUnit]::Pixel
Now it works as expected

Related

JQVMAP Country Coloring

I am using JQVMAP at here. When I have a country that has members I desire to change that country's color without mousing over it, as the map is displayed.
I am using the following sql to get the countries and the number of their members. My question is what do I do, once I have a country, to change that countries map color? All countries will have the same color.
$result=mysql_query("SELECT COUNT(profile3.organizations) total_org, LEFT(countryCODEconversions.Code, 2) FROM profile3, countryCODEconversions WHERE TRIM(MID(countryCODEconversions.Code, 4, 147)) = profile3.country GROUP by profile3.country");
//if(mysql_num_rows($result)>0){
$counter = "";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC))
{
foreach ($line as $value) {
$counter += 1;
$value = stripslashes($value);
if ($counter == 1){$total = nl2br($value);}
if ($counter == 2){
$counter = 0;
$countryCode = strtolower($value);
?>
gdpOrgData['<?=$countryCode?>']=("<?=$total?>");
<?
Normaly, after loading the map you can set the color of countries that need a different color like this:
jQuery(document).ready(function() {
jQuery('#vmap').vectorMap('set', 'colors', {lt: '#8c9622',
sv: '#8c9622',
yr: '#8c9622'});
});
You could use PHP to generate the list in this script. Just make sure to load it after the map is loaded.
I hope this points you in the correct direction.

How to get image using structure and template to get title,small and large image

I am using liferay 6.1.20.
Structure variable demo_image : type Document and Media
here is my template code. It is not fetching uuid or groupId from url !
#set ($dlLocalService = $serviceLocator.findService("com.liferay.portlet.documentlibrary.service.DLAppLocalService"))
#set ($url = $getterUtil.getString($demo_image.getData()))
#set ($uuid = $getterUtil.getString($httpUtil.getParameter($url, "uuid", false)))
#set ($groupId = $getterUtil.getLong($httpUtil.getParameter($url, "groupId", false)))
#set ($imageObj = $dlLocalService.getFileEntryByUuidAndGroupId($uuid,$groupId))
#set ($imageSmallid = $imageObj.getSmallImageId())
#set ($imageLargeid = $imageObj.getLargeImageId())
#set ($imageTitle = $imageObj.getTitle())
#set ($imageDescription = $imageObj.getDescription())
#set ($urlLargeImage = "/documents/imageLargeid")
#set ($urlSmallImage = "/documents/imageSmallid")
$imageTitle
<img src="$urlSmallImage" rel="$imageTitle" alt="$imageTitle" />
Check value of $url for your image, does this URL contain uuid & groupId if yes you should get the values. else if url contains imageId try using different method from service util.
Also try using DLFileE‌​ntryLocalService instead of DLAppLocalService
Hope this helps you find your solution !

PerlTk canvas + pixel manipulation

I'm having some problems understanding how the image types in PerlTk work.
I basically want a way to create an "empty" image (for example fully white) and then manipulate the pixel data. I need to able to change a pixel to black or white.
I've tried a few approaches but non of them seem to work. Documentation seems to be pretty scarce and very old. This is closest I've got.
#args name, width, height, data
my $bitmap = $mw->DefineBitmap('cells', 1, 1, pack("b1", "1"));
#args x-pos, y-pos, bitmap-name
$canvas->createBitmap(0, 0, -bitmap => 'cells');
Another idea I had was to use a Photo element but I couldn't find any documentation on how to create one with the "-data" option.
Any help is appreciated.
Use the put() method if you have to set single pixels. Here's a complete example:
use Tk;
my $mw = tkinit;
my $p = $mw->Photo(-width => 100, height => 100);
my $l = $mw->Label(-image => $p, -border => 0)->pack;
for (0..99) {
$p->put("#000000", -to => $_,$_);
$p->put("#000000", -to => 100-$_,$_);
}
MainLoop;

Powershell: Freezing GUI

Just a quick one. I have a problem with a simple tool that I've created that gets the CPU usage for a set amount of time with a small box that appears to display the % of CPU being used (I've stripped out the GUI for the code below).
function loop
{
$get = read-host
for($start = 0; $start -le 100;$start++)
{
cls
$pro_percentage = Get-WmiObject win32_processor -computer $get -property Loadpercentage | select loadpercentage
$percentage = "Processor usage is: " + $pro_percentage.loadpercentage + "%"
$percentage
}
}
loop
There's a few other bits to the GUI that I've created but I've noticed one majour problem, and this goes for other GUI apps that I have created. Whenever the 'go' button is pressed to start the script from the dialog box, the GUI freezes. The menu bar that I've created inside the GUI freezes and no other button can be pressed.
Am I supposed to run each function in a different thread? Something like that?
Thanks
Try to add:
[System.Windows.Forms.Application]::DoEvents()
in your loop. Quick and dirty, however.

ImageMagick/Perl sorting images by Pixel width/height

Hi I am having trouble finding any info on how to list images by pixel width or height with Image Magick. what I want to do is filter out images that are less than a specified size of pixel width or height. This is done through a perl script and any help is appreciated.
Based on some code I use for other stuff:
use strict;
use warnings;
use Image::Magick;
use Win32::Autoglob;
my $max_cols = 640;
my $max_rows = 480;
IMAGE:
for my $image_name (#ARGV) {
my $image = Image::Magick->new;
my $result = $image->Read($image_name);
die "Failed to read $image_name - $result" if $result;
my ($cols, $rows) = $image->Get('columns', 'rows');
next IMAGE if $cols > $max_cols;
next IMAGE if $rows > $max_rows;
# your processing here...
}
Use identify utility from ImageMagick to obtain width and height.
Install the PerlMagick perl module from
http://www.imagemagick.org/script/perl-magick.php
Use code similar to the Example Script
examples from that web page to read each image.
Query the number of rows and columns in each image using
$image->Get('rows')
and
$image->Get('columns') and skip images that are too small.

Resources