RMagick convert image with alpha - rmagick

I'm trying to convert an image to 25% opacity via RMagick. The following works from the command line but I can't figure out how to do it in Ruby.
convert input.png -alpha on -channel A -evaluate set 25% +channel output.png
I've tried messing with Magick::AlphaChannelType::ActivateAlphaChannel but can't figure out how to chain the commands together. Any help would be greatly appreciated!

plz try this function to solve your problem
def watermark(opacity = 0.25, size = 'input')
manipulate! do |img|
logo = Magick::Image.read("#{Rails.root}/app/assets/images/{size}.png").first
logo.alpha(Magick::ActivateAlphaChannel)
white_canvas = Magick::Image.new(logo.columns, logo.rows) { self.background_color = "none" }
white_canvas.alpha(Magick::ActivateAlphaChannel)
white_canvas.opacity = Magick::QuantumRange - (Magick::QuantumRange * opacity)
# Important: DstIn composite operation (white canvas + watermark)
logo_opacity = logo.composite(white_canvas, Magick::NorthWestGravity, 0, 0, Magick::DstInCompositeOp)
logo_opacity.alpha(Magick::ActivateAlphaChannel)
# Important: Over composite operation (original image + white canvas watermarked)
img = logo.composite(logo_opacity, Magick::NorthWestGravity, 0, 0, Magick::OverCompositeOp)
end
end

Related

How compare two images using sikuli in robotframework

am totaly new to the sikuli with robotframework. I have some want idea of click and action of the window based but i dont have the concept of compare the image using sikuli with robotframework. Can any one help me?
This is RaiMan from SikuliX.
I recommend to use
https://github.com/rainmanwy/robotframework-SikuliLibrary
I have developed a python script for image comparison, which gets two images to compare the images and write the difference.
You can use this as robot keyword for image comparison. Challenge is that you have to crop the image from desktop application. you can able to do this using robot framework sikuli library keyword crop region by providing x,y, width and height values
compare images.py
# importing the necessary packages
#from skimage.measure import compare_ssim
from skimage.metrics import structural_similarity
import argparse
import imutils
import cv2
import time
import logging
def Compare_Image(image1,image2,Original_image_path,Modified_image_path):
# Reading images
imageA = cv2.imread(image1)
imageB = cv2.imread(image2)
# convert the images to grayscale
grayA = cv2.cvtColor(imageA, cv2.COLOR_BGR2GRAY)
grayB = cv2.cvtColor(imageB, cv2.COLOR_BGR2GRAY)
#getting the structural similarity between the images
(score, diff) = structural_similarity(grayA, grayB, full=True)
diff = (diff * 255).astype("uint8")
print("SSIM: {}".format(score))
#Threshold differences
thresh = cv2.threshold(diff, 0, 255,
cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
# loop over the contours
for c in cnts:
#Displaying Rectangles on image difference
(x, y, w, h) = cv2.boundingRect(c)
cv2.rectangle(imageA, (x, y), (x + w, y + h), (0, 0, 255), 2)
cv2.rectangle(imageB, (x, y), (x + w, y + h), (0, 0, 255), 2)
# show the output images
image1=cv2.imshow("Original", imageA)
image2=cv2.imshow("Modified", imageB)
cv2.imwrite(Original_image_path, imageA)
cv2.imwrite(Modified_image_path, imageB)
# cv2.imshow("Diff", diff)
# cv2.imshow("Thresh", thresh)
#cv2.waitKey(0)
#cv2.destroyAllWindows()
#Validating and Logging Image Results
if score==1.0:
print("Reference and Test images are same")
else:
print("Reference and Test images are different")
Sample.robot
* Setting *
Library compare_Images.py
* Test Cases *
Check_Image_Compare
Compare Image path_to_image1\\img1.png path_to_image2\\image2.png
path_to_saveorginalimage1\\orgimage.png path_to_savemodifiedimage\\modifiedimage.png
Log <img src="path_to_saveorginalimage1\\orgimage.png"> HTML
Log <img src="path_to_savemodifiedimage\\modifiedimage.png"> HTML
On executing the python script it will give two images (original image- image1 to compare Modified image- image2 to compare) which will be saved in specified location and logged as in robot file above.

Finding the largest blob in a black/white image

I have this picture:
I want to create a mask from this image, to place on top of the original image. The mask I want to obtain is the black part at the top.
I tried to use simpleBlobDetector from OpenCV to try to detect the white part as one big blob. I do not obtain the results I am hoping for and am unsure what to do.
R has been used, but my question is not specifically on how to achieve this in R. The result I have is below the code.
library(Rvision)
x <- simpleBlobDetector(im, min_threshold = 0, max_threshold = 255)
plot(x)
I do not understand why those three black boxes are selected as blobs, while there are a lot more of those black boxes that are not selected.
EDIT: when I add blob_color = 255 so white blobs are searched, nothing is detected.
You can do something like this using OpenCV:
// read input image
Mat inputImg = imread("test1.tif", IMREAD_GRAYSCALE);
// create binary image
Mat binImg;
threshold(inputImg, binImg, 254, 1, THRESH_BINARY_INV);
// compute connected components
Mat labelImg;
connectedComponents(binImg, labelImg, 8, CV_16U);
// compute histogram
Mat histogram;
int histSize = 256;
float range[] = { 0, 256 } ;
const float* histRange = { range };
calcHist(&labelImg, 1, 0, Mat(), histogram, 1, &histSize, &histRange, true, false);
// retrieve maximal population
float maxVal = 0;
int maxIdx;
for (int i=1; i<histSize; ++i) {
if (histogram.at<float>(i) > maxVal) {
maxVal = histogram.at<float>(i);
maxIdx = i;
}
}
// create output mask with bigest population
Mat resImg;
threshold(labelImg, labelImg, maxIdx, 0, THRESH_TOZERO_INV);
threshold(labelImg, resImg, maxIdx-1, 1, THRESH_BINARY);
// write result
imwrite("res.tif", resImg);
And you should obtain something like this:
I think you can convert input to bianry, then extract connected components, compute associated histogram and simply keep (by thresholding) histogram class with highest population
Regards

Image compare autoit [duplicate]

I am looking for a way to find duplicate images using AutoIt. I've looked into PixelSearch and SearchImage but neither do exactly what I need them to do.
I am trying to compare 2 images by filename and see if they are the same image (a duplicate). The best way I've thought to do it would be to:
1) Get both image sizes in pixels
2) Use a while loop to get the color of each pixel and store it in an array
3) Check to see if both arrays are equal to each other.
Does anybody have any ideas on how to achieve this?
I just did some more research on this subject and built a small UDF based on a few answers I read. (Mainly based off of monoceres's answer on AutoItScript.com). I figured I would post my solution here to help any future developers!
CompareImagesUDF.au3
Func _CompareImages($ciImageOne, $ciImageTwo)
_GDIPlus_Startup()
$fname1=$ciImageOne
If $fname1="" Then Exit
$fname2=$ciImageTwo
If $fname2="" Then Exit
$bm1 = _GDIPlus_ImageLoadFromFile($fname1)
$bm2 = _GDIPlus_ImageLoadFromFile($fname2)
; MsgBox(0, "bm1==bm2", CompareBitmaps($bm1, $bm2))
Return CompareBitmaps($bm1, $bm2)
_GDIPlus_ImageDispose($bm1)
_GDIPlus_ImageDispose($bm2)
_GDIPlus_Shutdown()
EndFunc
Func CompareBitmaps($bm1, $bm2)
$Bm1W = _GDIPlus_ImageGetWidth($bm1)
$Bm1H = _GDIPlus_ImageGetHeight($bm1)
$BitmapData1 = _GDIPlus_BitmapLockBits($bm1, 0, 0, $Bm1W, $Bm1H, $GDIP_ILMREAD, $GDIP_PXF32RGB)
$Stride = DllStructGetData($BitmapData1, "Stride")
$Scan0 = DllStructGetData($BitmapData1, "Scan0")
$ptr1 = $Scan0
$size1 = ($Bm1H - 1) * $Stride + ($Bm1W - 1) * 4
$Bm2W = _GDIPlus_ImageGetWidth($bm2)
$Bm2H = _GDIPlus_ImageGetHeight($bm2)
$BitmapData2 = _GDIPlus_BitmapLockBits($bm2, 0, 0, $Bm2W, $Bm2H, $GDIP_ILMREAD, $GDIP_PXF32RGB)
$Stride = DllStructGetData($BitmapData2, "Stride")
$Scan0 = DllStructGetData($BitmapData2, "Scan0")
$ptr2 = $Scan0
$size2 = ($Bm2H - 1) * $Stride + ($Bm2W - 1) * 4
$smallest = $size1
If $size2 < $smallest Then $smallest = $size2
$call = DllCall("msvcrt.dll", "int:cdecl", "memcmp", "ptr", $ptr1, "ptr", $ptr2, "int", $smallest)
_GDIPlus_BitmapUnlockBits($bm1, $BitmapData1)
_GDIPlus_BitmapUnlockBits($bm2, $BitmapData2)
Return ($call[0]=0)
EndFunc ;==>CompareBitmaps
Now to compare imagages, all you have to do is include the CompareImagesUDF.au3 file and call the function.
CompareImagesExample.au3
#Include "CompareImagesUDF.au3"
; Define the two images (They can be different file formats)
$img1 = "Image1.jpg"
$img2 = "Image2.jpg"
; Compare the two images
$duplicateCheck = _CompareImages($img1, $img2)
MsgBox(0,"Is Duplicate?", $duplicateCheck)
If you want to find out if both images are an exact match, regardless if names are the same or different, use the built-in Crypt function _Crypt_HashFile with MD2 or MD5 to make a hash of both files and compare that.

pixelsearch clicking in middle?

it mostly clicks only in side (which is the sides pixels of a square) any idea how can click the middle area inside of pixelsearch? heres what i done but it wont work
$greenbox = PixelSearch(0, 0, #DesktopWidth, #DesktopHeight, 0x00FF00)
If isArray($greenbox) then
newX := greenbox[0] + 25
newY := greenbox[1] + 25
MouseMove($newX[0],$newY[1], 0)
MouseClick("Left")
$NewX and $NewY are not Arrays.
Try like this :
MouseMove($newX,$newY, 0)
MouseClick("Left")
or simplest :
MouseClick("Left,$newX,$newY)

I'm trying to get the pixel colour for a C4 image, how do I access the image colour matrix? c4framework

In the discussion of the colour colorMatrix:bias it reads :
This filter performs a matrix multiplication, as follows, to transform the color vector:
s.r = dot(s, redVector) s.g = dot(s, greenVector) s.b = dot(s, blueVector) s.a = dot(s, alphaVector) s = s + bias
Is there any way to gain access to the data values for the various colour vectors?
The discussion you're referring to, in the C4 documentation, refers to the process that a filter uses for calculating a matrix multiplication. This is actually just a description of what the filter does to the colors in the image when it gets applied.
In fact, what's happening under the hood is that the colorMatrix: method sets up a CIFilter called CIColorMatrix and applies this to a C4Image. Unfortunately the source code for the CIColorMatrix filter isn't provided by Apple.
So, a longwinded answer to your question is:
You can't access color components for pixels in a C4Image through the CIColorMatrix filter. But, the C4Image class has a property called CGImage (e.g. yourC4Image.CGImage) which you can use to get pixel data.
A good, simple technique can be found HERE
EDIT:
I got obsessed last night with this question, and added these two methods to the C4Image class:
Method for loading pixel data:
-(void)loadPixelData {
NSUInteger width = CGImageGetWidth(self.CGImage);
NSUInteger height = CGImageGetHeight(self.CGImage);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
bytesPerPixel = 4;
bytesPerRow = bytesPerPixel * width;
rawData = malloc(height * bytesPerRow);
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), self.CGImage);
CGContextRelease(context);
}
And a method for accessing pixel color:
-(UIColor *)colorAt:(CGPoint)point {
if(rawData == nil) {
[self loadPixelData];
}
NSUInteger byteIndex = bytesPerPixel * point.x + bytesPerRow * point.y;
CGFloat r, g, b, a;
r = rawData[byteIndex];
g = rawData[byteIndex + 1];
b = rawData[byteIndex + 2];
a = rawData[byteIndex + 3];
return [UIColor colorWithRed:RGBToFloat(r) green:RGBToFloat(g) blue:RGBToFloat(b) alpha:RGBToFloat(a)];
}
That's how I would apply the techniques from the other post I mentioned.

Resources