I am trying to add a label/annotation text (where the background colour of the text is transparent) to an existing image.
I have tried a couple of different approaches but I keep getting a black background colour.
If anyone could point me in the right direction, I would greatly appreciate it.
Attempt 1:
using (var images = new MagickImageCollection())
using (var img = new MagickImage(imgBytes))
{
img.Resize(imageDto.Width, imageDto.Height);
using (var imgText = new MagickImage(MagickColors.None, imageDto.Width, imageDto.Height))
{
var labelSettings = new MagickReadSettings()
{
BackgroundColor = MagickColors.None,
Font = "Arial",
FontPointsize = imageDto.FontSize,
FillColor = MagickColors.Blue,
BorderColor = MagickColors.None,
};
imgText.Read("label:" + imageDto.WatermarkText, labelSettings);
img.Composite(imgText, Gravity.South);
img.Write($"{Guid.NewGuid().ToString()}.png");
return img.ToBase64();
}
}
Attempt 2:
using (var img = new MagickImage(imgBytes))
{
img.Resize(imageDto.Width, imageDto.Height);
// Load the original image and add it to the collection.
images.Add(img);
// Text label watermark settings
var labelSettings = new MagickReadSettings()
{
BackgroundColor = new MagickColor(MagickColors.Transparent),
Font = "Arial",
FontPointsize = imageDto.FontSize,
FillColor = MagickColors.Blue
};
// Create the label image.
var label = new MagickImage($"label:{imageDto.WatermarkText}", labelSettings);
// Extent the width of the label to match the width of the original image.
label.Extent(img.Width, 0, Gravity.Center);
label.Transparent(MagickColors.Black);
// Add the label to the collection.
images.Add(label);
// Append the images to create the output image.
using (var result = images.AppendVertically())
{
result.Write($"{Guid.NewGuid().ToString()}.png");
return result.ToBase64();
}
}
Both attempts produce the same image with a black background (in the area where the text was added to the image)
.
Your first approach is probably the easiest one. But you should use the following overload instead: img.Composite(imgText, Gravity.South, CompositeOperator.Over); The default is CompositeOperator.In and that is not what you should use to get the label as an overlay.
In ImageMagick, you cannot draw transparency for text or background on an opaque image. So you have to draw a colored (black) rectangle, then flood fill it with transparency, then draw your colored text onto the transparent image. For example with your image:
convert image.png \
-draw "translate 250,250 fill black rectangle -50,-50 50,50 \
fill none matte 0,0 floodfill" \
-fill "rgba(255,0,0,1)" -pointsize 20 \
-gravity center -annotate +0+0 "TESTING" \
result.png
ADDITION:
If you only want the text, then leave out the background color and just write the text.
convert image.png \
-fill "red" -pointsize 20 \
-gravity center -annotate +0+0 "TESTING" \
result.png
Related
I am trying to get sketch effect and i have the imagemagick command line code as follows
convert 1.jpg -colorspace gray ( +clone -blur 0x8 \) +swap -compose divide -composite -linear-stretch 2%x20% cousincs.jpg
I am using gm module and I tried to extend gm,however it is not not accepting parenthesis, failing to recognize -linear-stretch resulting in two blurred images instead of one. I tried node-imagemagick native and wizardry but unable to achieve the desired functionality. Can anyone let me know how can I achieve this. Thanks in advance
Here is the code i tried with gm
var dir = __dirname + '/kar/';
var newName=uuid.v4()+".jpg";
imageMagick("2.jpg")
.clone()
.swap()
.compose('divide')
.composite()
.write(dir+newName, function(err,data){console.log("error is ",err)});
Here is the args.js
proto.clone = function clone () {
return this.out("\( +clone -blur 0x8\)");
}
proto.swap=function swap(){
return this.out("+swap");
}
proto.composite=function composite(){
return this.out("-composite -linear-stretch 2%x20%")
}
I'm trying to do image masking here is my output and code.
This is my masking reference image(Image size doesn't matter),
mask.png,
This is image on which i'm performing masking,
imggo.png,
This is the Output.
I'm using Swift, Here is my code...
override func viewDidLoad() {
super.viewDidLoad()
var maskRefImg : UIImage? = UIImage(named: "mask.png")
var maskImg :UIImage? = UIImage(named: "imggo.png")
var imgView: UIImageView? = UIImageView(frame: CGRectMake(20, 50, 99, 99))
imgView?.image = maskImage(maskRefImg!, maskImage: maskImg!)
self.view.addSubview(imgView!)
}
func maskImage(image:UIImage,maskImage:UIImage)-> UIImage{
var maskRef:CGImageRef = maskImage.CGImage
var mask:CGImageRef = CGImageMaskCreate(CGImageGetWidth(maskRef), CGImageGetHeight(maskRef), CGImageGetBitsPerComponent(maskRef), CGImageGetBitsPerPixel(maskRef), CGImageGetBytesPerRow(maskRef), CGImageGetDataProvider(maskRef), nil, true)
var masked:CGImageRef = CGImageCreateWithMask(image.CGImage, mask)
return UIImage(CGImage: masked)!
}
So,How can I make Go! image colourful.?
Would anyone provide code.?
You are calling the function maskImage with the wrong order of arguments:
The maskImage function wants the image to mask first, and then the mask. But when you call maskImage(maskRefImg!, maskImage: maskImg!) you have it exactly swapped.
So you need to call maskImage(maskImg!, maskImage: maskRefImg!)
I'm guessing that what you want to have is the tilted rectangle with the word "Go!" and that the result image should be exactly the same size as the mask image.
When you swap the images (as you must), the mask image is scaled to the "Go!" image size. But instead, you probably want the mask image centered over your "Go!" image. So you need to create a new image with the same size as your "Go!" image and draw the mask centered into that temporary image. You then use the temporary image as the actual mask to apply.
The example image when you swap the arguments also shows that the "outside" is also green. This probably because your mask image is transparent there and CGImageMaskCreate converts it to black. But the documentation of CGImageCreateWithMask basically tells you that the created image will blend the "Go!" image so that parts where your mask image is black will have the "Go!" image visible and where your mask image is white it will be transparent.
The step-by-step instructions thus are:
Create a new, temporary image that is of the same size as your input image (the "Go!" image).
Fill it with white.
Draw your mask image centered into the temporary image.
Create the actual mask by calling CGImageMaskCreate with the temporary image.
Call CGImageCreateWithMask with the "Go!" image as first argument and the actual mask we've just created as second argument.
The result might be too big (have a lot of transparency surrounding it). If you don't want that you need to crop the result image (e.g. to the size of your original mask image; make sure to crop to the center).
You can probably skip the CGImageCreateWithMask part if you immediately create the temporary image in the DeviceGray color space, as CGImageCreateWithMask wants the second argument to be an image in this color space. In that case, I suggest you modify your mask.png so it does not contain any transparency: it should be white where it's transparent now.
I have an image I want to partially mask (wallSprite), an image to act as a mask over it (wallMaskBox), and a node to hold both (wallCropNode). When I simply add both images as children of wallCropNode, both image display correctly:
var wallSprite = SKSpriteNode(imageNamed: "wall.png")
var wallCropNode = SKCropNode()
var wallMaskBox = SKSpriteNode(imageNamed: "blacksquaretiny.png")
wallMaskBox.zPosition = 100
wallCropNode.addChild(wallSprite)
wallCropNode.addChild(wallMaskBox)
gameplayContainerNode.addChild(wallCropNode)
But when I set the mask image as a maskNode property of the crop node:
var wallSprite = SKSpriteNode(imageNamed: "wall.png")
var wallCropNode = SKCropNode()
var wallMaskBox = SKSpriteNode(imageNamed: "blacksquaretiny.png")
wallMaskBox.zPosition = 100
wallCropNode.addChild(wallSprite)
wallCropNode.maskNode = wallMaskBox
gameplayContainerNode.addChild(wallCropNode)
the wallSprite image disappears entirely, instead of being partly cropped. Any ideas?
The issue is your black square image is completely opaque. Some (or all) of its pixels should be transparent (i.e., alpha = 0). The pixels that correspond to the mask node's transparent pixels will be masked out (i.e., not rendered) in the cropped node. To demonstrate this, I used your code to create the following.
Here's the original image:
Here's the mask image that I used for the maskNode. Note that the white regions are transparent (i.e., alpha = 0). From Apple's documentation,
When rendering its children, each pixel is verified against the
corresponding pixel in the mask. If the pixel in the mask has an alpha
value of less than 0.05, the image pixel is masked out. Any pixel not
rendered by the mask node is automatically masked out.
and here's the cropped node. I took a screenshot of the scene from the iPhone 6 simulator.
in a school project i would like to do the following step to have a watermaked image in matlab
extract the edges from an image
insert a mark on this edge
reconstruct the image
extract the mark
could some one give me a link to have a good idea how to do it or help me to do that?
thank you in advance
You want to add a watermark to an image? Why not just overlay the whole thing.
if you have an image
img = imread('myimage.jpg')
wm = imread('watermark.jpg')
You can just resize the watermark to the size of the image
wm_rs = imresize(wm, [size(img,1) size(img,2)], 'lanczos2');
img_wm(wm_rs ~= 0) = wm_rs; %This sets non-black pixels to be the watermark. (You'll have to slightly modify this for color images)
If you want to put it on the edges of the image, you can extract them like this
edges = edge(rgb2gray(img),'canny')
Then you can set the pixels where the edges exist to be watermark pixels
img_wm = img;
img_wm(edges ~= 0) = wm_rs(edges~=0);
Instead of direct assignment you can play around with using a mix of the img and wm_rs pixel values if you want transparency.
You'll probably have to adjust some of what I said to color images, but most should be the same.
Here, is a nice and simple example how you can embed watermarks using MATLAB (in the spatial domain): http://imageprocessingblog.com/digital-watermarking/
see example below(R2017b or later release):
% your params
img = imread('printedtext.png');
Transparency = 0.6;
fontColor = [1,1,1]; % RGB,range [0,1]
position = [700,200];
%% add watermark
mask = zeros(size(img),'like',img);
outimg = insertText(mask,position,'china', ...
'BoxOpacity',0,...
'FontSize',200,...
'TextColor', 'white');
bwMask = imbinarize(rgb2gray(outimg));
finalImg = labeloverlay(img,bwMask,...
'Transparency',Transparency,...
'Colormap',fontColor);
imshow(finalImg)
http://yester-place.blogspot.com/2008/11/opencv_12.html
the code is use to adjust the brightness and contrast of gray image.
How can i adjust it with the color image, that is, the result is color image.
thank you
You may want to switch from RGB color space to HSV color space. In this case, you would change the brightness of the image by changing the value of the H component of your image and then convert it back.
RGB is not a suitable color space for manipulation.
The function you might want to use is (using python):
def RGB2HSV(imgRGB):
"""
Converts an iplImage in RGB to HSV color scale, same size, same number of channels.
"""
if imgRGB == None:
print "imgRGB is void.Exiting . . ."
return None
if imgRGB.nChannels < 3:
print "imgRGB is single channel. Exiting . . ."
return None
dims = imageInfo(imgRGB)
imgHSV = cv.CreateImage( dims, cv.IPL_DEPTH_8U, imgRGB.nChannels)
cv.CvtColor(imgRGB, imgHSV, cv.CV_RGB2HSV)
return imgHSV