getPixel-method - how do i get the R value of RGB? - apache-flex

i have a greyscale image and i want to scan the pixels out of the Image and this is what i get :
var i:int;
var j:int;
for (i = 0; i < img.contentWidth ; i++)
{
for(j = 0; j < img.contentHeight; j++){
pixeldaten.addItem({x:i,y:j,pixel:bmd.getPixel(i,j)});
}
}
but the table doesn't look like RGB Values . (R , B , and G must be the same)
: example

getPixel should return the hex value value of the pixel, you could then do something like
// get the red value
bmd.getPixel(i,j) >> 16

//for Image processing
Bitmap myBitmap = new Bitmap(CurrentBitmap);
int imgH = myBitmap.Height;
int imgW = myBitmap.Width;
ARed = new double[imgH, imgW];
AGreen = new double[imgH, imgW];
ABlue = new double[imgH, imgW];
doubles = new double[imgH, imgW];
var max = new double[imgH, imgW];
var min = new double[0, 0];
//seperating each RGB components
for (int x = 0; x < imgH; x++)
{
for (int y = 0; y < imgW; y++)
{
Color color = myBitmap.GetPixel(x, y);
// things we do with pixelColor
//ARed[x][y] = myBitmap.GetPixel >> 16;
ARed[x, y] = color.R;
ABlue[x, y] = color.B;
AGreen[x, y] = color.G;
max[x, y] = ARed[x, y];
}
}

Bitmap bmp = new Bitmap(pictureBox1.Image);
bmp.getPixel(i,j).R

Related

First page is blackened after adding watermark

Page is blackened after adding watermark in case of some pdf files . Please see attached image.
What could be the reason , and possible fix.
see the blacked out page image
It does not happen for all the files but for some files only.
Code is here in dotnetfiddle.
var _pdfInBytes = File.ReadAllBytes("c:\\test\\test123.pdf");
string watermarkText = "This watermark text on left side";
var coordinates = new Point(25, 200);
using (var pdfNewDoc = new PdfDocument())
{
using (var pdfImport = PdfReader.Open(new MemoryStream(_pdfInBytes, true), PdfDocumentOpenMode.Import))
{
if (pdfImport.PageCount == 0)
{
return;
}
foreach (var pg in pdfImport.Pages)
{
pdfNewDoc.AddPage(pg);
}
var page = pdfNewDoc.Pages[0];
// overlapping trick #165910
var xOffset = 100.0;
for (var index = 0; index < page.Contents.Elements.Count; index++)
{
var stream = page.Contents.Elements.GetDictionary(index).Stream;
var x = GetMinXOffsetDraft(stream.ToString());
if (xOffset > x)
{
xOffset = x;
}
}
xOffset *= 0.6; // magic number :)
// blank page trick #165910
if (page.CropBox.IsEmpty && !page.MediaBox.IsEmpty)
{
page.CropBox = page.MediaBox;
}
// Get an XGraphics object for drawing beneath the existing content
var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
var tf = new XTextFormatter(gfx);
var xFont = new XFont("Arial", 10, XFontStyle.Regular);
// Get watermark text size
var wmSize = gfx.MeasureString(watermarkText, xFont);
// Middle Y coordinate
var wmY = (gfx.PageSize.Height - wmSize.Width) / 2;
var coords = new XPoint(page.CropBox.Location.X + (xOffset < coordinates.X ? xOffset : coordinates.X),
page.CropBox.Location.Y + (coordinates.Y > wmY ? coordinates.Y : wmY));
// Define a rotation transformation at the center of the page
gfx.TranslateTransform(coordinates.X, coordinates.Y);
gfx.RotateTransform(90);
gfx.TranslateTransform(-coordinates.X, -coordinates.Y);
// Create brush
var brushColor = Color.Red;
var brush1= new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
brush1.Overprint = false;
XBrush brush =
new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
var rect = new XRect(coordinates.X, coordinates.Y, gfx.PageSize.Height - coordinates.Y,
coordinates.X);
tf.DrawString(watermarkText, xFont, brush, rect);
byte[] outputBytes = null;
using (var outStream = new MemoryStream())
{
pdfNewDoc.Save(outStream, false);
outputBytes = outStream.ToArray();
}
File.WriteAllBytes("c:\\test\\test-"+DateTime.Now.ToString("ddmmyyyyhhmmss") +".pdf", outputBytes);
private double GetMinXOffsetDraft(string v)
{
var result = 100.0;
using (var str = new StringReader(v))
{
var s = str.ReadLine();
do
{
var sarr = s?.Split(' ');
if (sarr?.Length == 7 && sarr[6] == "Tm")
{
var x = double.Parse(sarr[4]);
x = x < 0 ? 200 : x;
result = result > x ? x : result;
}
s = str.ReadLine();
} while (s != null);
}
return result;
} var _pdfInBytes = File.ReadAllBytes("c:\\test\\test123.pdf");
string watermarkText = "This watermark text on left side";
var coordinates = new Point(25, 200);
using (var pdfNewDoc = new PdfDocument())
{
using (var pdfImport = PdfReader.Open(new MemoryStream(_pdfInBytes, true), PdfDocumentOpenMode.Import))
{
if (pdfImport.PageCount == 0)
{
return;
}
foreach (var pg in pdfImport.Pages)
{
pdfNewDoc.AddPage(pg);
}
var page = pdfNewDoc.Pages[0];
// overlapping trick #165910
var xOffset = 100.0;
for (var index = 0; index < page.Contents.Elements.Count; index++)
{
var stream = page.Contents.Elements.GetDictionary(index).Stream;
var x = GetMinXOffsetDraft(stream.ToString());
if (xOffset > x)
{
xOffset = x;
}
}
xOffset *= 0.6; // magic number :)
// blank page trick #165910
if (page.CropBox.IsEmpty && !page.MediaBox.IsEmpty)
{
page.CropBox = page.MediaBox;
}
// Get an XGraphics object for drawing beneath the existing content
var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
var tf = new XTextFormatter(gfx);
var xFont = new XFont("Arial", 10, XFontStyle.Regular);
// Get watermark text size
var wmSize = gfx.MeasureString(watermarkText, xFont);
// Middle Y coordinate
var wmY = (gfx.PageSize.Height - wmSize.Width) / 2;
var coords = new XPoint(page.CropBox.Location.X + (xOffset < coordinates.X ? xOffset : coordinates.X),
page.CropBox.Location.Y + (coordinates.Y > wmY ? coordinates.Y : wmY));
// Define a rotation transformation at the center of the page
gfx.TranslateTransform(coordinates.X, coordinates.Y);
gfx.RotateTransform(90);
gfx.TranslateTransform(-coordinates.X, -coordinates.Y);
// Create brush
var brushColor = Color.Red;
var brush1= new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
brush1.Overprint = false;
XBrush brush =
new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
var rect = new XRect(coordinates.X, coordinates.Y, gfx.PageSize.Height - coordinates.Y,
coordinates.X);
tf.DrawString(watermarkText, xFont, brush, rect);
byte[] outputBytes = null;
using (var outStream = new MemoryStream())
{
pdfNewDoc.Save(outStream, false);
outputBytes = outStream.ToArray();
}
File.WriteAllBytes("c:\\test\\test-"+DateTime.Now.ToString("ddmmyyyyhhmmss") +".pdf", outputBytes);
private double GetMinXOffsetDraft(string v)
{
var result = 100.0;
using (var str = new StringReader(v))
{
var s = str.ReadLine();
do
{
var sarr = s?.Split(' ');
if (sarr?.Length == 7 && sarr[6] == "Tm")
{
var x = double.Parse(sarr[4]);
x = x < 0 ? 200 : x;
result = result > x ? x : result;
}
s = str.ReadLine();
} while (s != null);
}
return result;
}

Qt3D: Texture is black

I'm trying to render frames captured by 3D scanner using Qt3D. Mesh is constructed right in geometry but it's shown black.
Below is my function where I convert vertices, texture coordinates, normals and add result object to a Scene. For debug purposes I'm trying to map texture from one source .png file to all the frames. But it still looks black. Normalizing texture coordinates vector didn't help.
Please take a look at my code and clarify what I'm doing wring. Thanks in advance.
Qt3DCore::QEntity* object = new Qt3DCore::QEntity(parent);
Qt3DRender::QGeometryRenderer* renderer = new Qt3DRender::QGeometryRenderer(object);
Qt3DRender::QGeometry* geometry = new Qt3DRender::QGeometry(renderer);
Qt3DRender::QBuffer* vertexBuffer = new Qt3DRender::QBuffer(geometry);
Qt3DRender::QBuffer* indexBuffer = new Qt3DRender::QBuffer(geometry);
Qt3DRender::QAttribute* positionAttribute = new Qt3DRender::QAttribute(geometry);
Qt3DRender::QAttribute* normalAttribute = new Qt3DRender::QAttribute(geometry);
Qt3DRender::QAttribute* texCoordAttribute = new Qt3DRender::QAttribute(geometry);
Qt3DRender::QAttribute* indexAttribute = new Qt3DRender::QAttribute(geometry);
const quint32 stride = (3 + 3 + 2) * sizeof(float);
positionAttribute->setName(Qt3DRender::QAttribute::defaultPositionAttributeName());
positionAttribute->setDataType(Qt3DRender::QAttribute::Float);
positionAttribute->setDataSize(3);
positionAttribute->setAttributeType(Qt3DRender::QAttribute::VertexAttribute);
positionAttribute->setBuffer(vertexBuffer);
positionAttribute->setByteOffset(0);
positionAttribute->setByteStride(stride);
normalAttribute->setName(Qt3DRender::QAttribute::defaultNormalAttributeName());
normalAttribute->setDataType(Qt3DRender::QAttribute::Float);
normalAttribute->setDataSize(3);
normalAttribute->setAttributeType(Qt3DRender::QAttribute::VertexAttribute);
normalAttribute->setBuffer(vertexBuffer);
normalAttribute->setByteOffset(3 * sizeof(float));
normalAttribute->setByteStride(stride);
texCoordAttribute->setName(Qt3DRender::QAttribute::defaultTextureCoordinateAttributeName());
texCoordAttribute->setDataType(Qt3DRender::QAttribute::Float);
texCoordAttribute->setDataSize(2);
texCoordAttribute->setAttributeType(Qt3DRender::QAttribute::VertexAttribute);
texCoordAttribute->setBuffer(vertexBuffer);
texCoordAttribute->setByteOffset((3 + 3) * sizeof(float));
texCoordAttribute->setByteStride(stride);
indexAttribute->setAttributeType(Qt3DRender::QAttribute::VertexAttribute);
indexAttribute->setDataType(Qt3DRender::QAttribute::Int);
indexAttribute->setDataSize(3);
indexAttribute->setByteOffset(0);
indexAttribute->setBuffer(indexBuffer);
indexAttribute->setCount(indices.size());
QByteArray* vertexArray = new QByteArray;
const auto t = vertices.size();
const auto r = sizeof(VertexData);
const auto d = t * r;
vertexArray->resize(vertices.size() * sizeof(VertexData));
float* rawVertexArray = reinterpret_cast<float*>(vertexArray->data());
int index = 0;
for (int i = 0; i < vertices.size(); ++i)
{
rawVertexArray[index++] = vertices[i].position_.x();
rawVertexArray[index++] = vertices[i].position_.y();
rawVertexArray[index++] = vertices[i].position_.z();
rawVertexArray[index++] = vertices[i].normal_.x();
rawVertexArray[index++] = vertices[i].normal_.y();
rawVertexArray[index++] = vertices[i].normal_.z();
const auto x = vertices[i].texCoords_.x();
rawVertexArray[index++] = vertices[i].texCoords_.x();
const auto y = vertices[i].texCoords_.y();
rawVertexArray[index++] = vertices[i].texCoords_.y();
}
QByteArray* indexArray = new QByteArray;
indexArray->resize(indices.size() * sizeof(VertexData));
auto* rawIndexArray = reinterpret_cast<int*>(indexArray->data());
index = 0;
for (int i = 0; i < indices.size(); ++i)
{
rawIndexArray[index++] = indices[i].x();
rawIndexArray[index++] = indices[i].y();
rawIndexArray[index++] = indices[i].z();
}
vertexBuffer->setData(*vertexArray);
indexBuffer->setData(*indexArray);
geometry->addAttribute(positionAttribute);
geometry->addAttribute(normalAttribute);
geometry->addAttribute(texCoordAttribute);
geometry->addAttribute(indexAttribute);
renderer->setGeometry(geometry);
renderer->setInstanceCount(1);
renderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::TriangleFan);
object->addComponent(renderer);
// Texture
Qt3DRender::QTexture2D* targetTexture = new Qt3DRender::QTexture2D(renderer);
Qt3DRender::QTextureImage* textureImage = new Qt3DRender::QTextureImage(targetTexture);
Qt3DExtras::QDiffuseSpecularMaterial* material = new Qt3DExtras::QDiffuseSpecularMaterial(renderer);
//Qt3DExtras::QNormalDiffuseSpecularMapMaterial* material = new Qt3DExtras::QNormalDiffuseSpecularMapMaterial();
textureImage->setMirrored(true);
textureImage->setSource(QUrl::fromLocalFile("D://Calibration tool//app-calibration-tool//output//1.jpg"));
targetTexture->addTextureImage(textureImage);
material->setDiffuse(QVariant::fromValue<Qt3DRender::QAbstractTexture *>(targetTexture));
material->setAmbient(QColor(255, 255, 255, 1));
material->setSpecular(QColor(255, 255, 255, 1));
material->setTextureScale(4);
material->setAlphaBlendingEnabled(true);
const auto transform = new Qt3DCore::QTransform(renderer);
object->addComponent(transform);
object->addComponent(material);
return parent;

color points based on what side of line they are on

I am trying to make a little algorithm that colors a point a certain color based on what side of a line the point is on. This is what i have at the moment. The code doesnt give any errors, but the colors also arent correct for the dots.. Could someone point out to me what i am doing wrong?
See the code:
PVector[] points;
void setup() {
size(500, 500);
points = new PVector[10];
for (int i = 0; i < points.length; i++) {
points[i] = new PVector(random(0, width), random(0, height));
}
ExtremesLine(points);
}
void ExtremesLine(PVector[] pts) {
float maxx = 0, minx = width+1;
PVector min = new PVector(), max = new PVector();
ArrayList<PVector> groupA = new ArrayList<PVector>(), groupB = new ArrayList<PVector>();
for (int i = 0; i < pts.length; i++) {
if (pts[i].x > maxx) {
maxx = pts[i].x;
max = pts[i];
}
if (pts[i].x < minx) {
minx = pts[i].x;
min = pts[i];
}
}
PVector divisionLine = new PVector();
PVector.sub(max, min, divisionLine);
PVector normal = new PVector(-divisionLine.y, divisionLine.x).normalize();
for (int i = 0; i < pts.length; i++) {
float s = PVector.dot(normal, pts[i].copy().normalize());
if ( s < 0) groupA.add(pts[i]);
else if ( s > 0) groupB.add(pts[i]);
}
fill(0);
line(min.x, min.y, max.x, max.y);
for (int i = 0; i < groupA.size(); i++) {
fill(255, 0, 0);
ellipse(groupA.get(i).x, groupA.get(i).y, 10, 10);
}
for (int i = 0; i < groupB.size(); i++) {
fill(0, 0, 255);
ellipse(groupB.get(i).x, groupB.get(i).y, 10, 10);
}
}
As you can see from the images below sometimes it works but 90% of the time it doesnt. First image is the correct result, second image is the incorrect result
If there is anything unclear pls let me know so i can clarify!
You need to dot with vectors from min:
replace
float s = PVector.dot(normal, pts[i].copy().normalize());
by
float s = PVector.dot(normal, pts[i].copy().sub(min).normalize());
and it will work as expected:
Tangentially, since min and max are Processing built-ins, are you sure that you want to use them as variable names?

Paperjs inserting segments to a rectangle gives strange result

I am trying to add random segments along the path of a rectangle. Here is my jsfiddle http://jsfiddle.net/hhND7/1/
<canvas id='canvas' resize style='' style='padding:0; margin:0;'></canvas>
<script type="text/paperscript" canvas="canvas" >
var rect = new Path.Rectangle({x:200, y:100}, new Size(80, 100))
rect.strokeColor = 'gray'
rect.selected = true;
var pathCuts = rands(20, 0, 360).sort(function(a,b){return a - b});
var tArr = [];
for ( var i=0; i<pathCuts.length; i++){
var loc = rect.getLocationAt(pathCuts[i]);
tArr.push(loc.point);
var sE = new Path.Circle(loc.point, 2);
sE.strokeColor = 'red';
}
rect.insertSegments(1, tArr);
function rands(n, min, max) {
var range = max - min;
if (range < n)
throw new RangeError("Specified number range smaller than count requested");
function shuffle() {
var deck = [], p, t;
for (var i = 0; i < range; ++i)
deck[i] = i + min;
for (i = range - 1; i > 0; --i) {
p = Math.floor(Math.random() * i);
t = deck[i];
deck[i] = deck[p];
deck[p] = t;
}
return deck.slice(0, n);
}
function find() {
var used = {}, rv = [], r;
while (rv.length < n) {
r = Math.floor(Math.random() * range + min);
if (!used[r]) {
used[r] = true;
rv.push(r);
}
}
return rv;
}
return range < 3 * n ? shuffle() : find();
}
</script>
I think the problem is with the insertSegments function. But i can not find a solution.
If you want it to still look like the original polygon, you need to sort in the positions of the original segments. Since you can replace a path's segments with an array of curveLocation , you can just add the locations of these points to tArr, then sort by each element by it's offset:
var pathCuts = rands(20, 0, rect.length);
var tArr = [];
for ( var i=0; i<pathCuts.length; i++){
var loc = rect.getLocationAt(pathCuts[i]);
tArr.push(loc);
var sE = new Path.Circle(loc.point, 2);
sE.strokeColor = 'red';
}
for ( var i = 0, l = rect.segments.length; i < l; i++){
tArr.push(rect.segments[i].location);
}
tArr.sort(function(a,b){return a.offset - b.offset})
rect.segments = tArr;

ZedGraph labels

In ZedGraph, how do I show text labels for each point and in the XAxis all together?
If I do
myPane.XAxis.Type = AxisType.Text;
myPane.XAxis.Scale.TextLabels = array_of_string;
I get labels on the XAxis like this
And if I do
for (int i = 0; i < myCurve.Points.Count; i++)
{
PointPair pt = myCurve.Points[i];
// Create a text label from the Y data value
TextObj text = new TextObj(
pt.Y.ToString("f0"), pt.X, pt.Y + 0.1,
CoordType.AxisXYScale, AlignH.Left, AlignV.Center);
text.ZOrder = ZOrder.A_InFront;
text.FontSpec.Angle = 0;
myPane.GraphObjList.Add(text);
}
I get labels on the curve, like this
But if I do both at the same time, labels on the curve disappear.
Is there a way to combine both kind of labels?
I've changed my answer after you clarified the question.
You just have to remember to position the labels correctly:
<%
System.Collections.Generic.List<ZedGraphWebPointPair> points = new System.Collections.Generic.List<ZedGraphWebPointPair>();
for (int i = 0; i < 15; i++)
{
// Let's have some fun with maths
points.Add(new ZedGraphWebPointPair
{
X = i,
Y = Math.Pow(i - 10, 2) * -1 + 120
});
}
System.Collections.Generic.List<string> XAxisLabels = new System.Collections.Generic.List<string>();
TestGraph.CurveList.Add(new ZedGraphWebLineItem { Color = System.Drawing.Color.Red });
TestGraph.XAxis.Scale.FontSpec.Size = 9;
int j = 1;
foreach (ZedGraphWebPointPair point in points)
{
// Add the points we calculated
TestGraph.CurveList[0].Points.Add(point);
// Add the labels for the points
TestGraph.GraphObjList.Add(new ZedGraphWebTextObj
{
Location =
{
CoordinateFrame = ZedGraph.CoordType.XChartFractionYScale,
// Make sure we position them according to the CoordinateFrame
X = Convert.ToSingle(j) / points.Count - 0.05f,
Y = Convert.ToSingle(point.Y) + 3f,
AlignV = ZedGraph.AlignV.Top
},
Text = point.Y.ToString(),
FontSpec = { Angle = 90, Size = 9, Border = { IsVisible = false } }
});
// Add the labels for the XAxis
XAxisLabels.Add(String.Format("P{0}", j));
j++;
}
TestGraph.RenderGraph += delegate(ZedGraphWeb zgw, System.Drawing.Graphics g, ZedGraph.MasterPane mp)
{
ZedGraph.GraphPane gp = mp[0];
gp.XAxis.Type = ZedGraph.AxisType.Text;
gp.XAxis.Scale.TextLabels = XAxisLabels.ToArray();
};
%>
That code will produce this graph:
If the axis type is text, the code below is easier to get x-coordinates of the points ;)
for (int tPoint = 0; tPoint < curve.Points.Count; tPoint++)
{
TextObj text = new TextObj(curve.Points[tPoint].Y.ToString(), curve.Points[tPoint].X, curve.Points[tPoint].Y + 10);
}

Resources