How to tell if an image is 90% black? - image

I have never done image processing before.
I now need to go through many jpeg images from a camera to discard those very dark (almost black) images.
Are there free libraries (.NET) that I can use? Thanks.

Aforge is a great image processing library. Specifically the Aforge.Imaging assembly.
You could try to apply a threshold filter, and use an area or blob operator and do your comparisons from there.

I needed to do the same thing. I came up with this solution to flag mostly black images. It works like a charm. You could enhance it to delete or move the file.
// set limit
const double limit = 90;
foreach (var img in Directory.EnumerateFiles(#"E:\", "*.jpg", SearchOption.AllDirectories))
{
// load image
var sourceImage = (Bitmap)Image.FromFile(img);
// format image
var filteredImage = AForge.Imaging.Image.Clone(sourceImage);
// free source image
sourceImage.Dispose();
// get grayscale image
filteredImage = Grayscale.CommonAlgorithms.RMY.Apply(filteredImage);
// apply threshold filter
new Threshold().ApplyInPlace(filteredImage);
// gather statistics
var stat = new ImageStatistics(filteredImage);
var percentBlack = (1 - stat.PixelsCountWithoutBlack / (double)stat.PixelsCount) * 100;
if (percentBlack >= limit)
Console.WriteLine(img + " (" + Math.Round(percentBlack, 2) + "% Black)");
filteredImage.Dispose();
}
Console.WriteLine("Done.");
Console.ReadLine();

Related

How to achieve high quality cropped images from canvas?

I am desperately searching for a good cropping tool. There are a bunch out there, for example:
Croppic
Cropit
Jcrop
The most important thing that I am trying to find is a cropping tool, that crops images without making the cropped image low in resolution. You can hack this by using the canvas tag by resizing the image. This way the image itself stays native, only the representation is smaller.
DarkroomJS was also something near the solution, but, unfortunately, the downloaded demo did not work. I'll try to figure out whats wrong. Does someone know some great alternatives, or how to get the cropped images in...let's say "native" resolution?
Thanks in advance!
You are relying on the cropping tool to provide an interface for the users. the problem is that the image returned is sized to the interface and not the original image. Rather than me sifting through the various API's to see if they provide some way of controlling this behaviour (I assume at least some of them would) and because it is such a simple procedure I will show how to crop the image manually.
To use JCrop as an example
Jcrop provides various events for cropstart, cropmove, cropend... You can add a listener to listen to these events and keep a copy of the current cropping interface state
var currentCrop;
jQuery('#target').on('cropstart cropmove cropend',function(e,s,crop){
currentCrop = crop;
}
I don't know where you have set the interface size and I am assuming the events return the crop details at the interface scale
var interfaceSize = { //you will have to work this out
w : ?,
h : ?.
}
Your original image
var myImage = new Image(); // Assume you know how to load
So when the crop button is clicked you can create the new image by scaling the crop details back to the original image size, creating a canvas at the cropped size, drawing the image so that the cropped area is corectly positioned and returning the canvas as is or as a new image.
// image = image to crop
// crop = the current cropping region
// interfaceSize = the size of the full image in the interface
// returns a new cropped image at full res
function myCrop(image,crop,interfaceSize){
var scaleX = image.width / interfaceSize.w; // get x scale
var scaleY = image.height / interfaceSize.h; // get y scale
// get full res crop region. rounding to pixels
var x = Math.round(crop.x * scaleX);
var y = Math.round(crop.y * scaleY);
var w = Math.round(crop.w * scaleX);
var h = Math.round(crop.h * scaleY);
// Assume crop will never pad
// create an drawable image
var croppedImage = document.createElement("canvas");
croppedImage.width = w;
croppedImage.height = h;
var ctx = croppedImage.getContext("2d");
// draw the image offset so the it is correctly cropped
ctx.drawImage(image,-x,-y);
return croppedImage
}
You then only need to call this function when the crop button is clicked
var croppedImage;
myButtonElement.onclick = function(){
if(currentCrop !== undefined){ // ensure that there is a selected crop
croppedImage = myCrop(myImage,currentCrop,interfaceSize);
}
}
You can convert the image to a dataURL for download, and upload via
imageData = croppedImage.toDataURL(mimeType,quality) // quality is optional and only for "image/jpeg" images

Finding size of images imported at runtime

I am currently loading images at runtime from directories stored in an XML file, and assigning them to RawImage components via the WWW class. While this is working fine, the image is skewed to fit into the new texture size.
I am wondering how to get an image’s original size or aspect ratio so that I can change the size of the image rect to suit. The images to be imported are at varying sizes and therefore the approach used needs to be responsive to the original size of imported images.
Any suggestions would be much appreciated. [Scripting in uJS]
Many thanks in advance, Ryan
function loadContextImage(texLocation : String)
{
if (!imageView.activeSelf)
{
imageView.SetActive(true);
}
var wwwDirectory = "file://" + texLocation; //this will probably need to change for other OS (PC = file:/ [I think?]) - **REVISE**
var newImgTex = new Texture2D(512, 512);
while(true){
var www : WWW = new WWW(wwwDirectory);
yield www;
www.LoadImageIntoTexture(newImgTex);
if (www.isDone){
break; //if done downloading image break loop
}
}
var imageRender : UI.RawImage = imageView.GetComponent.<RawImage>();
imageRender.texture = newImgTex;
}
If you cannot use an Image (for nay valid reasons), you can get the width and height of the texture:
WWW www = new WWW(url);
yield return www;
Texture2D tex = www.texture;
float aspectRatio = tex.height / tex.width;
rawImage.width = width;
rawImage.height = width * aspectRatio;
This should make the rect of the image of the appropriate ratio of the texture.
If you can use Image and preserveAspectRatio, you get it done by Unity. The result is not necessarily the same since it will keep the dimensions of the box and make the Sprite occupies as much space while keeping ratio.

How to improve display quality in pdf.js

I'm using open source library for PDF documents from mozilla(pdf.JS).
When i'm trying to open pdf documents with bad quality, viewer displays it with VERY BAD quality.
But if I open it in reader, or in browser (drag/drop into new window), whis document displays well
Is it possible to change?
Here is this library on github mozilla pdf.js
You just have to change the scaling of your pdf i.e. when rendering a page:
pdfDoc.getPage(num).then(function(page) {
var viewport = page.getViewport(scale);
canvas.height = viewport.height;
canvas.width = viewport.width;
...
It is the scale value you have to change. Then, the resulting rendered image will fit into the canvas given its dimensions e.g. in CSS. What this means is that you produce a bigger image, fit it into the container you had before and so you effectively improve the resolution.
There is renderPage function in web/viewer.js and print resolution is hard-coded in there as 150 DPI.
function renderPage(activeServiceOnEntry, pdfDocument, pageNumber, size) {
var scratchCanvas = activeService.scratchCanvas;
var PRINT_RESOLUTION = 150;
var PRINT_UNITS = PRINT_RESOLUTION / 72.0;
To change print resolution to 300 DPI, simply change the line below.
var PRINT_RESOLUTION = 300;
See How to increase print quality of PDF file with PDF.js viewer for more details.
Maybe it's an issue related with pixel ratio, it used to happen to me when device pixel ratio is bigger than 1 (for example iPhone, iPad, etc.. you can read this question for a better explanation.
Just try that file on PDF.js Viewer. If it works like expected, you must check how PDF.js works with pixel ratio > 1 here. What library basically does is:
canvas.width = viewport.width * window.devicePixelRatio;
canvas.styles.width = viewport.width + 'px'; // Note: The px unit is required here
But you must check how PDF.js works for better perfomance
I ran into the same issue and I used the intent option of renderContent to fix that.
const renderContext = {
intent: 'print',
// ....
}
var renderTask = page.render(renderContext);
As per docs renderContext accepts intent which supports three values - display, print or any. The default is display. When I used print instead the render quality was extremely good, at par with any desktop app.

opencv: change image size without effecting content size

I am getting image containing character after applying my image process. All these images (having character as content) have different size. I want to resize all images in same size without effecting it's content size. see below image:
http://techsture.com/img.jpg
I have tried some function to merge my source image with other white image but it needs both source images with same size. I need common size of images for further process.
Please guide me how can I convert my images to common size ??
Thank you
I would make a new image with the destination size, set a ROI in this new image to where you want the source image to show. Then use cvResize.
It should look something like:
int newWidth = 100;
int newHeight = 100;
CvRect rect;
IplImage* source = cvLoadImage("c:/myimage");
IplImage* dest = cvCreateImage(cvSize(newWidth,newHeight),source->depth,source->nChannels);
rect.x = newWidth/2 - source->width/2;
rect.y = newHeight/2 - source->height/2;
rect.width = source->width;
rect.height = source->height;
cvSetImageROI(dest,rect);
cvResize(source,dest);
cvResetImageROI(dest);

Photoshop Action to fill image to make a certain ratio

I am looking to make a photoshop action (maybe this isn't possible, any other application recommendations would be helpful as well). I want to take a collection of photos and make them a certain aspect ration, ex: 4:3.
So I have an image that is 150px wide by 200px high. What I would like to happen is the image's canvas is made to be 267px wide, with the new area filled with a certain color.
So there are two possibilities I can think of:
1) Photoshop actions could do this, but I would have to pull current height, multiply by 1.333333 and then put that value in the width box of the canvas resize. Is it possible to have calculated values in Photoshop actions?
2) Some other application has this feature built in.
Any help is greatly appreciated.
Wow, I see now (after writing the answer) that this was asked a long time ago. . . oh well. This script does the trick.
This Photoshop script will resize any image's canvas so that it has a 4:5 aspect ratio. You can change the aspect ratio applied by changing arWidth and arHeight. The fill color will be set to the current background color. You could create an action to open a file, apply this script, then close the file to do a batch process.
Shutdown Photoshop.
Copy this javascript into a new file named "Resize Canvas.jsx" in Photoshop's Presets\Scripts folder.
Start Photoshop and in the File - Scripts menu it should appear.
#target photoshop
main ();
function main ()
{
if (app.documents.length < 1)
{
alert ("No document open to resize.");
return;
}
// These can be changed to create images with different aspect ratios.
var arHeight = 4;
var arWidth = 5;
// Apply the resize to Photoshop's active (selected) document.
var doc = app.activeDocument;
// Get the image size in pixels.
var pixelWidth = new UnitValue (doc.width, doc.width.type);
var pixelHeight = new UnitValue (doc.height, doc.height.type);
pixelWidth.convert ('px');
pixelHeight.convert ('px');
// Determine the target aspect ratio and the current aspect ratio of the image.
var targetAr = arWidth / arHeight;
var sourceAr = pixelWidth / pixelHeight;
// Start by setting the current dimensions.
var resizedWidth = pixelWidth;
var resizedHeight = pixelHeight;
// The source image aspect ratio determines which dimension, if any, needs to be changed.
if (sourceAr < targetAr)
resizedWidth = (arWidth * pixelHeight) / arHeight;
else
resizedHeight = (arHeight * pixelWidth) / arWidth;
// Apply the change to the image.
doc.resizeCanvas (resizedWidth, resizedHeight, AnchorPosition.MIDDLECENTER);
}
Mind that the accepted answer from #user268911 may not work for you if the source image has different pixels/inch than 72. Because the UnitValue.convert function works correctly only with 72 px/inch. To be sure the conversion is correct for ever pixel/inch value, set baseUnit property as follows:
...
var pixelWidth = new UnitValue (doc.width, doc.width.type);
pixelWidth.baseUnit = UnitValue (doc.width.baseUnit, "in");
var pixelHeight = new UnitValue (doc.height, doc.height.type);
pixelHeight.baseUnit = UnitValue (doc.height.baseUnit, "in");
...
For more details about the conversion see "Converting pixel and percentage values" section of the Adobe JavaScript Tools Guide.
What languages do you know? ImageMagick has command line tools that can do this, but you'd need to know a scripting language to get the values and calculate the new ones.
For .NET, my company's product, DotImage Photo, is free and can do this (need to know C# or VB.NET)

Resources