Converting image to grayscale in windows phone 8 - windows-phone-7

How i can convert a normal image to Grayscale image in windows phone 8. Is there any provision for grayscale conversion is available in WritableBitmapEx.

try this extension method...
public static WriteableBitmap ToGrayScale(this WriteableBitmap bitmapImage)
{
for (var y = 0; y < bitmapImage.PixelHeight; y++)
{
for (var x = 0; x < bitmapImage.PixelWidth; x++)
{
var pixelLocation = bitmapImage.PixelWidth * y + x;
var pixel = bitmapImage.Pixels[pixelLocation];
var pixelbytes = BitConverter.GetBytes(pixel);
var bwPixel = (byte)(.299 * pixelbytes[2] + .587 * pixelbytes[1] + .114 * pixelbytes[0]);
pixelbytes[0] = bwPixel;
pixelbytes[1] = bwPixel;
pixelbytes[2] = bwPixel;
bitmapImage.Pixels[pixelLocation] = BitConverter.ToInt32(pixelbytes, 0);
}
}
return bitmapImage;
}

I don't think that there is a method, but you can convert it yourself. There are bunch of resources online on how to accomplish that. Start by reading this. One of the simpler methods could be:
for (int i = 0; i < oldBitmap.Pixels.Length; i++)
{
var c = oldBitmap.Pixels[i];
var a = (byte)(c >> 24);
var r = (byte)(c >> 16);
var g = (byte)(c >> 8);
var b = (byte)(c);
byte gray = (byte)((r * 0.3) + (g * 0.59) + (b * 0.11));
oldBitmap.Pixels[i] = (a << 24) | (gray << 16) | (gray << 8) | gray;
}
It's simple, quick, and you convert it in-place.

Related

How to speed up Get func in p5.js?

Is there any way to speed up this piece of code (simplified)? On my Dell m4700 laptop, it works for 1 minute and 10 seconds (the size of the canvas is 1000x1400 pixels).
pg = createGraphics(1000,1400);
pg.pixelDensity(1);
***
for(j=0;j<pg.height;j++){
for(i=0;i<pg.width;i++){
pg.stroke(cc=pg.get(i,j));
pg.point(i,j+4);
}
}
Without this line,
pg.stroke(cc=pg.get(i,j));
the code executes in milliseconds.
I made another version that works in 20 seconds, but for some reason the result is slightly different visually:
for(j=0;j<pg.height;j++){
pg.loadPixels();
for(i=0;i<pg.width;i++){
let pi = i + (j * pg.width);
let ri = pi * 4;
let cr = pg.pixels[ri];
let cg = pg.pixels[ri + 1];
let cb = pg.pixels[ri + 2];
let ca = pg.pixels[ri + 3];
pg.stroke(color(cr,cg,cb,ca));
pg.point(i,floor(j+4));
}
}
Big edit:
Ok, I miss read the question and was thinking in java's processing not p5js as the OP has properly indicated. So my answer was very wrong. Sorry.
But still the approach exists in p5js and is faster.
p5js store pixels in 1d array, 4 slots for each pixel:
[pix1R, pix1G, pix1B, pix1A, pix2R, pix2G, pix2B, pix2A...]
And also the pixel density mathers.
So the code is different, I belive you are looking for something like (no pg here, but the thinking is the same):
loadPixels();
let d = pixelDensity();
let imagesize = 4 * (width * d) * ((height) * d);
for (let i = 0; i <= imagesize; i += 4) {
let j = i + 16;//4*4
pixels[i] = pixels[j];
pixels[i + 1] = pixels[j + 1];
pixels[i + 2] = pixels[j + 2];
pixels[i + 3] = pixels[j + 3];
}
updatePixels();
Now, to access a given area in the array is a little convoluted, here an example
//the area data
const area_x = 35;
const area_y = 48;
const width_of_area = 180;
const height_of_area = 200;
//the pixel density
const d = pixelDensity();
loadPixels();
// those 2 first loops goes trough every pixel in the area
for (let x = area_x; x < width_of_area; x++) {
for (let y = area_y; y < height_of_area; y++) {
//here we go trough the pixels array to get each value of a pixel
for (let i = 0; i < d; i++) {
for (let j = 0; j < d; j++) {
// calculate the index of the 1d array for every pixel
// 4 values in the array for each pixel
// y times density times #of pixels plus
// x times density times #of pixels
index = 4 * ((y * d + j) * width * d + (x * d + i));
// You can assign raw values for rgb color
pixels[index] = 255;
pixels[index + 1] = 30;
pixels[index + 2] = 200;
pixels[index + 3] = 255;
}
}
}
}
updatePixels();
Both this examples are at p5js online editor:
1:https://editor.p5js.org/v-k-/sketches/GGVeZvCk7
2: https://editor.p5js.org/v-k-/sketches/kW9lXyK2n
Hope that helps, and sorry for the previus processing answer/code.
cheers

How to find the answer to a XOR hash if I have the key & one number

I have a little routine that makes up a cumulative XOR hash. It's as if it is a savings account which gets bigger, cumulatively daily.. but in this sense we're saying the answer is being generated cumulatively and the key is always present.
I have taken a string of chars
pseudo code:
char H[10] = { "ABCDEFGHI", "\0" };
and I used 9 32-bit numeric keys to hash them in XOR encryption.
I did it like this:
for (i;i<10;i++)
bitset<32> K ^= H[i] ^ NUMKEY[i];
Now this makes it impervious without the calculus plotting I did (see what I did there?) So K is an accumulation of calculus points, which are completely predictable according to calculus.
as far as I know, to undo it, I do
for (i;i<10;i++) {
X=0;
X ^= K ^ NUMKEY[i];
}
Is there other math involved? I think I have to take that X and do a little K - X to find the true derivative.
Here's the current routine I have for it. But I'm not getting what I'm looking for.
for_each (std::istreambuf_iterator<char>(in), \
std::istreambuf_iterator<char>(), \
[&] (long x) {
t=s_nop(t,0);
cred.push_back(t);
alpha = static_cast<long>(cred[size]);
delta = static_cast<long>(x);
lambda ^= (alpha ^ delta);
size++;
});
for (;i<bn;i++) {
alpha = static_cast<unsigned long>(cred[bn-1-i]);
int m = lambda.to_ulong(), n = alpha.to_ulong();
long hash1 = abs((m-n-1)%256-1);
delta = static_cast<unsigned long>(hash1);
btrace.push_back(hash1);
cout << hash1 << " ";
}
Please have a safe and Merry Christmas. Thank you in advance!
I think what you might really want is a one time pad. (the snippet is javascript as pseudocode moving in that direction)
//ignore these top 3 functions (they're just for printing output)
function appendLine(text, target, space, color) {
var line = document.createElement("div");
line.style.border = "1px solid " + color;
line.style.padding = line.style.margin = space;
line.style["font-family"] = "monospace";
line.appendChild(document.createTextNode(text));
target.appendChild(line);
return line;
}
function makeSection(title) {
var d = appendLine(title, document.body, "5px", "#dddddd");
var results = document.createElement("div");
d.appendChild(results);
return function(result) {
appendLine(result, results, "2px", "#eeeeee");
};
}
function toHex(arr) {
return arr.map(function(n){
var h = (n >>> 0).toString(16).toUpperCase();
while(h.length < 8) h = "0" + h;
return h;
}).join(",");
}
//your message
var H = "ABCDEFGHI".split("").map(function(c){return c.charCodeAt(0)});
//your secret encoding key
var NUMKEY = Array.apply(null, Array(9)).map(function(){return Math.random() * Math.pow(2, 32)});
//what you're doing
(function() {
var section = makeSection("what you're doing:");
section("ABCDEFGHI as array of 32bit numbers: " + toHex(H));
section("NUMKEY: " + toHex(NUMKEY));
var K = 0;
for (var i = 0; i < 10; i++) {
K ^= H[i] ^ NUMKEY[i];
}
section("K: " + toHex([K]));
var X = 0;
for (var i = 0; i < 10; i++) {
X ^= K ^ NUMKEY[i];
}
section("X: " + toHex([X]));
})();
//what you're trying to do
(function() {
var section = makeSection("what you're trying to do:");
section("ABCDEFGHI as array of 32bit numbers: " + toHex(H));
section("NUMKEY: " + toHex(NUMKEY));
var Hs_XORd = 0;
for (var i = 0; i < 10; i++) {
Hs_XORd ^= H[i];
}
section("H's XOR'd together: " + toHex([Hs_XORd]));
var NUMKEYs_XORd = 0;
for (var i = 0; i < H.length; i++) {
NUMKEYs_XORd ^= NUMKEY[i];
}
section("NUMKEY's XOR'd together: " + toHex([NUMKEYs_XORd]));
var K = NUMKEYs_XORd ^ Hs_XORd;
section("K: " + toHex([K]));
var X = K ^ NUMKEYs_XORd;
section("X (should be the same as H's XOR'd together): " + toHex([X]));
})();
//what I think you mean to be doing (one time pad)
(function() {
var section = makeSection("what I think you mean to be doing (one time pad):");
section("ABCDEFGHI as array of 32bit numbers: " + toHex(H));
section("NUMKEY: " + toHex(NUMKEY));
var K = [];
for (var i = 0; i < H.length; i++) {
K[i] = H[i] ^ NUMKEY[i];
}
section("K (encoded message using NUMKEY as one time pad): " + toHex(K));
var X = [];
for (var i = 0; i < K.length; i++) {
X[i] = K[i] ^ NUMKEY[i];
}
section("X (decoded message, should be the same as ABCDEFGHI): " + toHex(X));
})();

How to apply SoftLight blender between two images in OpenCV?

Regarding to this post on StackOverflow (and this too) I'm taking one normal image of a flower, then a white image and then I apply the SoftLight.
These are the images (flower and white image):
The result should be something similar of what I've got in GIMP:
but it's finally a white image.
I modified the code in order to put it inside a function, and this is my code:
// function
uint convSoftLight(int A, int B) {
return ((uint)((B < 128)?(2*((A>>1)+64))*((float)B/255):(255-(2*(255-((A>>1)+64))*(float)(255-B)/255))));
}
void function() {
Mat flower = imread("/Users/rafaelruizmunoz/Desktop/flower.jpg");
Mat white_flower = Mat::zeros(Size(flower.cols, flower.rows), flower.type());
Mat mix = Mat::zeros(Size(flower.cols, flower.rows), flower.type());
for (int i = 0; i < white_flower.rows; i++) {
for (int j = 0; j < white_flower.cols; j++) {
white_flower.at<Vec3b>(i,j) = Vec3b(255,255,255);
}
}
imshow("flower", flower);
imshow("mask_white", white_flower);
for (int i = 0; i < mix.rows; i++) {
for (int j = 0; j < mix.cols; j++) {
Vec3b vec = flower.at<Vec3b>(i,j);
vec[0] = convSoftLight(vec[0], 255); // 255 or just the white_flower pixel at (i,j)
vec[1] = convSoftLight(vec[1], 255); // 255 or just the white_flower pixel at (i,j)
vec[2] = convSoftLight(vec[2], 255); // 255 or just the white_flower pixel at (i,j)
mix.at<Vec3b>(i,j) = vec;
}
}
imshow("mix", mix);
}
What am I doing wrong?
Thank you.
EDIT: I've tried to flip the order (convSoftLight(B,A); instead convSoftLight(A,B)), but nothing happened (black image)
Based on the blender definitions: I rewrote my function:
uint convSoftLight(int A, int B) {
float a = (float)A / 255;
float b = (float)B / 255;
float result = 0;
if (b < 0.5)
result = 2 * a * b + pow(a,2) * (1 - 2*b);
else
result = 2 * a * (1-b) + sqrt(a) * (2*b - 1);
return (uint)255* result;
}
Here's how soft light might be implemented in Python (with OpenCV and NumPy):
import numpy as np
def applySoftLight(bottom, top, mask):
""" Apply soft light blending
"""
assert all(image.dtype == np.float32 for image in [bottom, top, mask])
blend = np.zeros(bottom.shape, dtype=np.float32)
low = np.where((top < 0.5) & (mask > 0))
blend[low] = 2 * bottom[low] * top[low] + bottom[low] * bottom[low] * (1 - 2 * top[low])
high = np.where((top >= 0.5) & (mask > 0))
blend[high] = 2 * bottom[high] * (1 - top[high]) + np.sqrt(bottom[high]) * (2 * top[high] - 1)
# alpha blending accroding to mask
result = bottom * (1 - mask) + blend * mask
return result
All matrices must be single channel 2D matrices converted into type np.float32. Mask is a "layer mask" in terms of GIMP/Photoshop.

Rescaling image in J2ME

I'm resizing a bird image using the following code:
private Image resizeImage(Image src) {
int srcWidth = src.getWidth();
int srcHeight = src.getHeight();
int screenWidth=getWidth()/3;
int screenHeight=getHeight()/3;
Image tmp = Image.createImage(screenWidth, srcHeight);
Graphics g = tmp.getGraphics();
int ratio = (srcWidth << 16) / screenWidth;
int pos = ratio/2;
//Horizontal Resize
for (int x = 0; x < screenWidth; x++) {
g.setClip(x, 0, 1, srcHeight);
g.drawImage(src, x - (pos >> 16), 0, Graphics.LEFT | Graphics.TOP);
pos += ratio;
}
Image resizedImage = Image.createImage(screenWidth, screenHeight);
g = resizedImage.getGraphics();
ratio = (srcHeight << 16) / screenHeight;
pos = ratio/2;
//Vertical resize
for (int y = 0; y < screenHeight; y++) {
g.setClip(0, y, screenWidth, 1);
g.drawImage(tmp, 0, y - (pos >> 16), Graphics.LEFT | Graphics.TOP);
pos += ratio;
}
return resizedImage;
}
The image is resized but it has white background along with it as shown. How to get only resized image with transparent background..?
Here is an Image scaling function I've been using. Includes transparency. Found here: http://willperone.net/Code/codescaling.php
public Image scale(Image original, int newWidth, int newHeight) {
int[] rawInput = new int[original.getHeight() * original.getWidth()];
original.getRGB(rawInput, 0, original.getWidth(), 0, 0, original.getWidth(), original.getHeight());
int[] rawOutput = new int[newWidth * newHeight];
// YD compensates for the x loop by subtracting the width back out
int YD = (original.getHeight() / newHeight) * original.getWidth() - original.getWidth();
int YR = original.getHeight() % newHeight;
int XD = original.getWidth() / newWidth;
int XR = original.getWidth() % newWidth;
int outOffset = 0;
int inOffset = 0;
for (int y = newHeight, YE = 0; y > 0; y--) {
for (int x = newWidth, XE = 0; x > 0; x--) {
rawOutput[outOffset++] = rawInput[inOffset];
inOffset += XD;
XE += XR;
if (XE >= newWidth) {
XE -= newWidth;
inOffset++;
}
}
inOffset += YD;
YE += YR;
if (YE >= newHeight) {
YE -= newHeight;
inOffset += original.getWidth();
}
}
rawInput = null;
return Image.createRGBImage(rawOutput, newWidth, newHeight, true);
}

How to convert the Cartesian coordinate to image coordinate in FreeType

Recently, I worded on OCR in Chinese characters, I wanna use FreeType(2.3.5) to collect the samples of character, here's my code :
FT_Library fontLibrary;
FT_Face fontFace;
int fontSize = 64;
// Initialize
FT_Init_FreeType(&fontLibrary);
FT_New_Face(fontLibrary, "C:\\Windows\\Fonts\\simhei.ttf", 0, &fontFace);
// Setup
FT_Select_Charmap(fontFace, FT_ENCODING_UNICODE);
FT_Set_Pixel_Sizes(fontFace, fontSize, 0);
FT_Load_Char(fontFace, 'H', FT_LOAD_RENDER);
// Retrieve data
FT_GlyphSlot & glyphSlot = fontFace->glyph;
FT_Bitmap charBitmap = glyphSlot->bitmap;
int charWidth = charBitmap.width;
int charHeight = charBitmap.rows;
unsigned char* charBuffer = charBitmap.buffer;
// Construct image
Mat fontImage(fontSize, fontSize, CV_8UC1);
fontImage = Scalar::all(0);
for (int y = 0; y < charHeight; y++)
{
int row = fontSize - glyphSlot->bitmap_top + y;
for (int x = 0; x < charWidth; x++)
{
int col = glyphSlot->bitmap_left + x;
fontImage.at<uchar>(row, col) = charBuffer[y*charWidth + x];
}
}
imshow("Font Image", fontImage);
waitKey(0);
// Uninitialize
FT_Done_Face(fontFace);
FT_Done_FreeType(fontLibrary);
The problem is : the character is not center aligned in image, the coordinate of character image looks strange, in this example, the coordinate of 'H' character is (fontSize = 64) :
bitmap_left = 3
bitmap_top = 44
bitmap.width = 26
bitmap.rows = 43
then convert to the coordinate of image :
ROI.left = bitmap_left = 3;
ROI.right = bitmap_left + bitmap.width = 29;
ROI.top = fontSize - bitmap_top = 20;
ROI.bottom = fontSize - bitmap_top + bitmap.rows = 63;
so the margin in 4-direction is :
ROI.leftMargin = 3;
ROI.rightMargin = 64 - 29 = 35;
ROI.topMargin = 20;
ROI.bottomMargin = 64 - 63 = 1;
IT IS NOT CENTER ALIGNED !!!
I solve the problem by myself, the left-top coordinate of image is stored in glyphSlot, here's the blog :
http://kang.blog.com/2013/09/21/how-to-convert-the-cartier-coordinate-to-image-coordinate-in-freetype/

Resources