Image Processing Java esp.Slicing - slice

im trying to convert an android code into java using netbeans as IDE.
all the other conversion is done. a single line is still remaining because i don't know what equivalent function can be use here.
public BufferedImage[] SeprateText(BufferedImage newb3)
{
Color clr1,clr2,clr3,clr4;
for(int iht=0;iht<newb3.getHeight()-1;iht++)
{
if(chk==false)
{
clr1 = new Color(newb3.getRGB(0, iht));
if(clr1==Color.RED)
{
chk=true;
}
}
clr2 = new Color(newb3.getRGB(5, iht));
clr3 = new Color(newb3.getRGB(5, iht));
if(chk && ( clr2 == Color.BLACK || clr3 ==Color.WHITE ))
{
if(!sind)
{
sind=true;
index[count]=iht;
}
location[count]++;
clr4 = new Color(newb3.getRGB(0, iht+1));
if(clr4==Color.RED)
{
chk=false;
endloc[count]=iht;
barray[count] = Bitmap.create(newb3,0,index[count],
newb3.getWidth(),location[count]);
// this is the line. i dont know what function of bufferedImage can replace it
count++;
sind=false;
}
}
}
}

Related

Attribute alignment after edit in AutoCAD

I have a simple routine that updates the text value of an attributereference. After the routine runs the values are updated in the drawing but the text is left justified and not centered. I have not been able to find any command that will cause AutoCAD to update the text location. So any help would be appreciated.
My Code
using (Transaction acTrans = db.TransactionManager.StartTransaction())
{
BlockTable bt = (BlockTable)acTrans.GetObject(db.BlockTableId, OpenMode.ForRead);
foreach (ObjectId oid in bt)
{
BlockTableRecord btr = (BlockTableRecord)acTrans.GetObject(oid, OpenMode.ForRead);
foreach (ObjectId o in btr)
{
if (o.ObjectClass.Name == "AcDbBlockReference")
{
BlockReference br = (BlockReference)acTrans.GetObject(o, OpenMode.ForRead);
BlockTableRecord b2 = (BlockTableRecord)acTrans.GetObject(br.BlockTableRecord, OpenMode.ForRead);
if (b2.Name == blockName)
{
AttributeCollection ac = br.AttributeCollection;
foreach (ObjectId i in ac)
{
AttributeReference ar = (AttributeReference)acTrans.GetObject(i, OpenMode.ForWrite);
string tagName = ar.Tag;
foreach (TestAutoCADCntrl.CBAttributeTag t in tags)
{
if (t.TagName == tagName)
{
ar.Justify = AttachmentPoint.MiddleCenter;
ar.AdjustAlignment(db);
ar.TextString = t.TagValue;
ar.DowngradeOpen();
}
}
}
br.RecordGraphicsModified(true);
}
}
}
}
acTrans.Commit();
Sorry, I have been searching for this issue for 3 days and found the answer right after i posted this question. For anyone else you just need to change the working database before you update the attribute text value.
foreach (TestAutoCADCntrl.CBAttributeTag t in tags)
{
if (t.TagName == tagName)
{
Database wdb = HostApplicationServices.WorkingDatabase; HostApplicationServices.WorkingDatabase = db;
ar.TextString = t.TagValue;
ar.AdjustAlignment(db);
HostApplicationServices.WorkingDatabase = wdb;
}
}

Dynamic web twain version 10.0

if i run my code in mozilla firefox after i click scan in UI select source window is opened and then it crashed.
bt the same code if i run on chrome it scan the image in the scanner after that if i click the scan on the new window it scan properly and crashed during file transfer and chrome tell a error message "a plugin (shockwave flash) isnt responding "
what may be the prob
function onScan(no_of_pages)
{
if (DWObject)
{
if (DWObject.SourceCount > 0)
{
DWObject.SelectSource();
DWObject.IfDisableSourceAfterAcquire = true;
DWObject.AcquireImage();
DWObject.MaxImagesInBuffer = no_of_pages;
}
else
alert("No TWAIN compatible drivers detected.");
}
}
function Dynamsoft_ChangeConfig(config){
config.onPrintMsg = g_DWT_PrintMsg;
}
function g_DWT_PrintMsg(strMessage) {
alert(strMessage);
}
function OnPostTransferCallback()
{
try{
if(DWObject.MaxImagesInBuffer == DWObject.HowManyImagesInBuffer)
{
DWObject.CloseSource();
sendToFlash() ;
}else
{
//TBD
}
}catch(err){
alert(err.message);
}
}
//Call back function from the
function sendToFlash()
{
try{
var flashMovie = window.document.flashContent;
flashMovie.sendToActionScript(DWObject.HowManyImagesInBuffer);
//document.getElementById("ICANSWF").sendToActionScript();
}catch(err){
alert(err.message);
}
}
//call from flash for uploading documents
function onUpload(serialNo)
{
//alert("upload the file");
var imageArr = new Array();
try{
var imageName;
var uploadPage;
var serverHost;
var CurrentPathName = unescape(location.pathname); // get current PathName in plain ASCII
var CurrentPath = CurrentPathName.substring(0, CurrentPathName.lastIndexOf("/") + 1);
uploadPage = CurrentPath+"TempUpload.php";
//uploadPage = CurrentPath+"UploadDocument.php";
//serverHost = "blabla";
//window.Plugin.HTTPPort =1451;
serverHost = "our host";
DWObject.HTTPPort = 80;
DWObject.IfSSL = false;
//alert(Plugin.HowManyImagesInBuffer);
for(var i=0;i < DWObject.HowManyImagesInBuffer;i++)
{
imageName = serialNo+"_"+(i+1)+".png";
DWObject.HTTPUploadThroughPost(serverHost,i,uploadPage,imageName);
if (DWObject.ErrorCode == 0)
{
//alert(imageName);
imageArr.push({"label":imageName,"source":"http://"+serverHost+":"+DWObject.HTTPPort+"/icanindonesia/AppData/Temp/"+imageName}); //Push image name and location in an array
}
else //succeded
{
alert(DWObject.ErrorString);
//imageArr[i] = imageName;
//alert(imageArr[i]);
}
}
}catch(err){
//alert("onUpload");
alert(err.message);
}
console.log(imageArr);
return imageArr;
}
function startDownload(url)
{
//var url='.zip';
window.open(url,'Download');
}
function openDocument(url){
window.open(url, '_blank',"ican image viewer");
}
#priya, this is Rachel from Dynamsoft.Thanks for using our Dynamic Web TWAIN SDK. Which version of Firefox and Chrome are you using? We now also have newer version of Dynamic Web TWAIN which you may try. Please contact our support team to get better help.

How to correct loop counters for maze algorithm?

I have figured out how to move my character around the maze using the algorithm I have written, but the count is not figuring correctly. At the end of each row my character moves up and down several times until the count reaches the specified number to exit the loop, then the character moves along the next row down until it reaches the other side and repeats the moving up and down until the count reaches the specified number again. Can anyone help me find why my count keeps getting off? The algorithm and the maze class I am calling from is listed below.
public class P4 {
public static void main(String[] args) {
// Create maze
String fileName = args[3];
Maze maze = new Maze(fileName);
System.out.println("Maze name: " + fileName);
// Get dimensions
int mazeWidth = maze.getWidth();
int mazeHeight = maze.getHeight();
// Print maze size
System.out.println("Maze width: " + mazeWidth);
System.out.println("Maze height: " + mazeHeight);
int r = 0;
int c = 0;
// Move commands
while (true){
for (c = 0; c <= mazeWidth; c++){
if (maze.moveRight()){
maze.isDone();
c++;
}
if (maze.isDone() == true){
System.exit(1);
}
if (maze.moveRight() == false && c != mazeWidth){
maze.moveDown();
maze.moveRight();
maze.moveRight();
maze.moveUp();
c++;
}
}
for (r = 0; r % 2 == 0; r++){
maze.moveDown();
maze.isDone();
if (maze.isDone() == true){
System.exit(1);
}
}
for (c = mazeWidth; c >= 0; c--){
if (maze.moveLeft()){
c--;
maze.isDone();
System.out.println(c);
}
if (maze.isDone() == true){
System.exit(1);
}
if (maze.moveLeft() == false && c != 0){
maze.moveDown();
maze.moveLeft();
maze.moveLeft();
maze.moveUp();
c--;
}
}
for (r = 1; r % 2 != 0; r++){
maze.moveDown();
maze.isDone();
if (maze.isDone() == true){
System.exit(1);
}
}
}
}
}
public class Maze {
// Maze variables
private char mazeData[][];
private int mazeHeight, mazeWidth;
private int finalRow, finalCol;
int currRow;
private int currCol;
private int prevRow = -1;
private int prevCol = -1;
// User interface
private JFrame frame;
private JPanel panel;
private Image java, student, success, donotpass;
private ArrayList<JButton> buttons;
// Maze constructor
public Maze(String fileName) {
// Read maze
readMaze(fileName);
// Graphics setup
setupGraphics();
}
// Get height
public int getHeight() {
return mazeHeight;
}
// Get width
public int getWidth() {
return mazeWidth;
}
// Move right
public boolean moveRight() {
// Legal move?
if (currCol + 1 < mazeWidth) {
// Do not pass?
if (mazeData[currRow][currCol + 1] != 'D')
{
currCol++;
redraw(true);
return true;
}
}
return false;
}
// Move left
public boolean moveLeft() {
// Legal move?
if (currCol - 1 >= 0) {
// Do not pass?
if (mazeData[currRow][currCol - 1] != 'D')
{
currCol--;
redraw(true);
return true;
}
}
return false;
}
// Move up
public boolean moveUp() {
// Legal move?
if (currRow - 1 >= 0) {
// Do not pass?
if (mazeData[currRow - 1][currCol] != 'D')
{
currRow--;
redraw(true);
return true;
}
}
return false;
}
// Move down
public boolean moveDown() {
// Legal move?
if (currRow + 1 < mazeHeight) {
// Do not pass?
if (mazeData[currRow + 1][currCol] != 'D')
{
currRow++;
redraw(true);
return true;
}
}
return false;
}
public boolean isDone() {
// Maze solved?
if ((currRow == finalRow) && (currCol == finalCol))
return true;
else
return false;
}
private void redraw(boolean print) {
// Wait for awhile
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
if (print)
System.out.println("Moved to row " + currRow + ", column " + currCol);
// Compute index and remove icon
int index = (prevRow * mazeWidth) + prevCol;
if ((prevRow >= 0) && (prevCol >= 0)) {
buttons.get(index).setIcon(null);
}
// Compute index and add icon
index = (currRow * mazeWidth) + currCol;
if ((currRow == finalRow) && (currCol == finalCol))
buttons.get(index).setIcon(new ImageIcon(success));
else
buttons.get(index).setIcon(new ImageIcon(student));
// Store previous location
prevRow = currRow;
prevCol = currCol;
}
// Set button
private void setButton(JButton button, int row, int col) {
if (mazeData[row][col] == 'S') {
button.setIcon(new ImageIcon(student));
currRow = row;
currCol = col;
} else if (mazeData[row][col] == 'J') {
button.setIcon(new ImageIcon(java));
finalRow = row;
finalCol = col;
} else if (mazeData[row][col] == 'D') {
button.setIcon(new ImageIcon(donotpass));
}
}
// Read maze
private void readMaze(String filename) {
try {
// Open file
Scanner scan = new Scanner(new File(filename));
// Read numbers
mazeHeight = scan.nextInt();
mazeWidth = scan.nextInt();
// Allocate maze
mazeData = new char[mazeHeight][mazeWidth];
// Read maze
for (int row = 0; row < mazeHeight; row++) {
// Read line
String line = scan.next();
for (int col = 0; col < mazeWidth; col++) {
mazeData[row][col] = line.charAt(col);
}
}
// Close file
scan.close();
} catch (IOException e) {
System.out.println("Cannot read maze: " + filename);
System.exit(0);
}
}
// Setup graphics
private void setupGraphics() {
// Create grid
frame = new JFrame();
panel = new JPanel();
panel.setLayout(new GridLayout(mazeHeight, mazeWidth, 0, 0));
frame.add(Box.createRigidArea(new Dimension(0, 5)), BorderLayout.NORTH);
frame.add(panel, BorderLayout.CENTER);
// Look and feel
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
// Configure window
frame.setSize(mazeWidth * 100, mazeHeight * 100);
frame.setTitle("Maze");
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setAlwaysOnTop(true);
// Load and scale images
ImageIcon icon0 = new ImageIcon("Java.jpg");
Image image0 = icon0.getImage();
java = image0.getScaledInstance(100, 100, Image.SCALE_DEFAULT);
ImageIcon icon1 = new ImageIcon("Student.jpg");
Image image1 = icon1.getImage();
student = image1.getScaledInstance(100, 100, Image.SCALE_DEFAULT);
ImageIcon icon2 = new ImageIcon("Success.jpg");
Image image2 = icon2.getImage();
success = image2.getScaledInstance(100, 100, Image.SCALE_DEFAULT);
ImageIcon icon3 = new ImageIcon("DoNotPass.jpg");
Image image3 = icon3.getImage();
donotpass = image3.getScaledInstance(100, 100, Image.SCALE_DEFAULT);
// Build panel of buttons
buttons = new ArrayList<JButton>();
for (int row = 0; row < mazeHeight; row++) {
for (int col = 0; col < mazeWidth; col++) {
// Initialize and add button
JButton button = new JButton();
Border border = new LineBorder(Color.darkGray, 4);
button.setOpaque(true);
button.setBackground(Color.gray);
button.setBorder(border);
setButton(button, row, col);
panel.add(button);
buttons.add(button);
}
}
// Show window
redraw(false);
frame.setVisible(true);
}
}
One error I can see in your code is that you're incrementing your c counter more often than you should. You start with it managed by your for loop, which means that it will be incremented (or decremented, for the leftward moving version) at the end of each pass through the loop. However, you also increment it an additional time in two of your if statements. That means that c might increase by two or three on a single pass through the loop, which is probably not what you intend.
Furthermore, the count doesn't necessarily have anything obvious to do with the number of moves you make. The loop code will always increase it by one, even if you're repeatedly trying to move through an impassible wall.
I don't really understand what your algorithm is supposed to be, so I don't have any detailed advice for how to fix your code.
One suggestion I have though is that you probably don't ever want to be calling methods on your Maze class without paying attention to their return values. You have a bunch of places where you call isDone but ignore the return value, which doesn't make any sense. Similarly, you should always be checking the return values from your moveX calls, to see if the move was successful or not. Otherwise you may just blunder around a bunch, without your code having any clue where you are in the maze.

a puzzle game algorithm in as3

I am creating game like http://www.puzzlegames.org/814games-Connect-2-Game-game.html. so what should i add in connected() function?
fB and sB are First and second button selected.
fBN and sBN are names of those buttons.
allNull() makes fB,sB, fBN, sBN null.
function onClick(e:MouseEvent):void {
if (! another) {
another = true;
fB = e.target;
fBN = e.target.name;
}
else {
sB = e.target;
sBN = e.target.name;
if (fBN == sBN)
{
allNull();
}
else if (connected())
{
fB.removeEventListener(MouseEvent.MOUSE_DOWN, onClick);
sB.removeEventListener(MouseEvent.MOUSE_DOWN, onClick);
fB.alpha = 0;
sB.alpha = 0;
pairCount++;
allNull();
if (pairCount == 25)
{
gameOver = false;
showScore();
endGame();
}
}
another = false;
}
}
Please help. I am trying to solve this problem since 15 days.
Thanks in advance.

In Selenium, how to compare images?

As i have been asked to automate our Company's website using Selenium Automation tooL.
But i am new to Selenium tool to proceed with, but i have learnt the basics of Selenium IDE and RC. But i am very much confused with how to compare actual and original images as we usually do in other automation tools. How do we come to a result that there bug in the website? Its obviously through image comparison but i wonder as selenium is one of the very popular tools but it doesn't have image comparing option. On the other hand i doubt whether my way of proceeding with the automation process is correct! Could somebody please help me out..
Thanks in Advance!!
Sanjay S
I had simillar task. I needed to compare more than 3000 images on a WebPage.
First of all I scrolled page to load all images:
public void compareImage() throws InterruptedException {
driver.get(baseUrl);
driver.manage().window().maximize();
JavascriptExecutor executor = (JavascriptExecutor) driver;
Long previousHeight;
Long currentHeight;
do {
previousHeight = (Long) executor.executeScript("return document.documentElement.scrollHeight");
executor.executeScript("window.scrollBy(0, document.documentElement.scrollHeight)");
Thread.sleep(500);
currentHeight = (Long) executor.executeScript("return document.documentElement.scrollHeight");
} while (Long.compare(previousHeight, currentHeight) != 0);
after I compared size of all images with first image(or you can just write size):
List<WebElement> images = driver.findElements(By.cssSelector("img[class='playable']"));
List<String> errors = new LinkedList<>();
int imgWidth, imgHeight, elWidth, elHeight;
int imgNum = 0;
imgWidth = images.get(0).getSize().getWidth();
imgHeight = images.get(0).getSize().getHeight();
for (WebElement el : images) {
imgNum++;
elWidth = el.getSize().getWidth();
elHeight = el.getSize().getHeight();
if (imgWidth != elWidth || imgHeight != elHeight) {
errors.add(String.format("Picture # %d has incorrect size (%d : %d) px"
, imgNum, elWidth, elHeight));
}
}
for (String str : errors)
System.out.println(str);
if (errors.size() == 0)
System.out.println("All images have the same size");
}
Since you mention knowledge about Selenium RC, you can easily extend Selenium's capability using a library for your chosen programming language. For instance, in Java you can use the PixelGrabber class for comparing two images and assert their match.
imagemagick and imagediff are also two good tools to use for image matching. You would require Selenium RC and a programming language knowledge to work with it.
Image comparison on C#. To get exact results I recommend to disable anti aliasing browser feature before taking screenshots, otherwise pixels each time are a little bit different drawn. For example HTML canvas element options.AddArgument("disable-canvas-aa");
private static bool ImageCompare(Bitmap bmp1, Bitmap bmp2, Double TolerasnceInPercent)
{
bool equals = true;
bool flag = true; //Inner loop isn't broken
//Test to see if we have the same size of image
if (bmp1.Size == bmp2.Size)
{
for (int x = 0; x < bmp1.Width; ++x)
{
for (int y = 0; y < bmp1.Height; ++y)
{
Color Bitmap1 = bmp1.GetPixel(x, y);
Color Bitmap2 = bmp2.GetPixel(x, y);
if (Bitmap1.A != Bitmap2.A)
{
if (!CalculateTolerance(Bitmap1.A, Bitmap2.A, TolerasnceInPercent))
{
flag = false;
equals = false;
break;
}
}
if (Bitmap1.R != Bitmap2.R)
{
if (!CalculateTolerance(Bitmap1.R, Bitmap2.R, TolerasnceInPercent))
{
flag = false;
equals = false;
break;
}
}
if (Bitmap1.G != Bitmap2.G)
{
if (!CalculateTolerance(Bitmap1.G, Bitmap2.G, TolerasnceInPercent))
{
flag = false;
equals = false;
break;
}
}
if (Bitmap1.B != Bitmap2.B)
{
if (!CalculateTolerance(Bitmap1.B, Bitmap2.B, TolerasnceInPercent))
{
flag = false;
equals = false;
break;
}
}
}
if (!flag)
{
break;
}
}
}
else
{
equals = false;
}
return equals;
}
This C# function calculates tolerance
private static bool CalculateTolerance(Byte FirstImagePixel, Byte SecondImagePixel, Double TolerasnceInPercent)
{
double OneHundredPercent;
double DifferencesInPix;
double DifferencesPercentage;
if (FirstImagePixel > SecondImagePixel)
{
OneHundredPercent = FirstImagePixel;
}
else
{
OneHundredPercent = SecondImagePixel;
}
if (FirstImagePixel > SecondImagePixel)
{
DifferencesInPix = FirstImagePixel - SecondImagePixel;
}
else
{
DifferencesInPix = SecondImagePixel - FirstImagePixel;
}
DifferencesPercentage = (DifferencesInPix * 100) / OneHundredPercent;
DifferencesPercentage = Math.Round(DifferencesPercentage, 2);
if (DifferencesPercentage > TolerasnceInPercent)
{
return false;
}
return true;
}

Resources