Question

In: Computer Science

package imageblocks; import java.awt.Color; import utils.Picture; public class ImageBlocks { static Color BLACK = new Color(0,0,0);...


package imageblocks;

import java.awt.Color;

import utils.Picture;

public class ImageBlocks {
static Color BLACK = new Color(0,0,0);
static Color WHITE = new Color(255,255,255);
private int height;
private int width;
boolean [][] visited;
Picture pic;
  
public ImageBlocks(Picture pic) {
   this.pic = pic;
   height = pic.height();
   width = pic.width();
}
  
  
private boolean isBlack(int x,int y){
return pic.get(x,y).equals(BLACK);
}
private boolean isWhite(int x,int y){
return pic.get(x,y).equals(WHITE);
}
  
/**

* METHOD TO BE COMPLETED
* count the number of image blocks in the given image
* Counts the number of connected blocks in the binary digital image
* @return number of black blocks
*/
public int countConnectedBlocks(){
       //TODO
   }

}

== Picture Class for Help ==

public final class Picture implements ActionListener {

private BufferedImage image; // the rasterized image

private JFrame frame; // on-screen view

private String filename; // name of file

private boolean isOriginUpperLeft = true; // location of origin

private final int width, height; // width and height

   /**

   * Initializes a blank <tt>w</tt>-by-<tt>h</tt> picture, where each pixel is black.

   */

public Picture(int w, int h) {

if (w < 0) throw new IllegalArgumentException("width must be nonnegative");

if (h < 0) throw new IllegalArgumentException("height must be nonnegative");

width = w;

height = h;

image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

// set to TYPE_INT_ARGB to support transparency

filename = w + "-by-" + h;

}

   /**

   * Initializes a new picture that is a deep copy of <tt>pic</tt>.

   */

public Picture(Picture pic) {

width = pic.width();

height = pic.height();

image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

filename = pic.filename;

for (int x = 0; x < width(); x++)

for (int y = 0; y < height(); y++)

image.setRGB(x, y, pic.get(x, y).getRGB());

}

   /**

   * Initializes a picture by reading in a .png, .gif, or .jpg from

   * the given filename or URL name.

   */

public Picture(String filename) {

this.filename = filename;

try {

// try to read from file in working directory

File file = new File(filename);

if (file.isFile()) {

image = ImageIO.read(file);

}

// now try to read from file in same directory as this .class file

else {

URL url = getClass().getResource(filename);

if (url == null) { url = new URL(filename); }

image = ImageIO.read(url);

}

width = image.getWidth(null);

height = image.getHeight(null);

}

catch (IOException e) {

// e.printStackTrace();

throw new RuntimeException("Could not open file: " + filename);

}

}

   /**

   * Initializes a picture by reading in a .png, .gif, or .jpg from a File.

   */

public Picture(File file) {

try { image = ImageIO.read(file); }

catch (IOException e) {

e.printStackTrace();

throw new RuntimeException("Could not open file: " + file);

}

if (image == null) {

throw new RuntimeException("Invalid image file: " + file);

}

width = image.getWidth(null);

height = image.getHeight(null);

filename = file.getName();

}

   /**

   * Returns a JLabel containing this picture, for embedding in a JPanel,

   * JFrame or other GUI widget.

   */

public JLabel getJLabel() {

if (image == null) { return null; } // no image available

ImageIcon icon = new ImageIcon(image);

return new JLabel(icon);

}

   /**

   * Sets the origin to be the upper left pixel.

   */

public void setOriginUpperLeft() {

isOriginUpperLeft = true;

}

   /**

   * Sets the origin to be the lower left pixel.

   */

public void setOriginLowerLeft() {

isOriginUpperLeft = false;

}

   /**

   * Displays the picture in a window on the screen.

   */

public void show() {

// create the GUI for viewing the image if needed

if (frame == null) {

frame = new JFrame();

JMenuBar menuBar = new JMenuBar();

JMenu menu = new JMenu("File");

menuBar.add(menu);

JMenuItem menuItem1 = new JMenuItem(" Save... ");

menuItem1.addActionListener(this);

menuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,

   Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));

menu.add(menuItem1);

frame.setJMenuBar(menuBar);

frame.setContentPane(getJLabel());

// f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

frame.setTitle(filename);

frame.setResizable(false);

frame.pack();

frame.setVisible(true);

}

// draw

frame.repaint();

}

   /**

   * Returns the height of the picture (in pixels).

   */

public int height() {

return height;

}

   /**

   * Returns the width of the picture (in pixels).

   */

public int width() {

return width;

}

   /**

   * Returns the color of pixel (<em>x</em>, <em>y</em>).

   */

public Color get(int x, int y) {

if (x < 0 || x >= width()) throw new IndexOutOfBoundsException("x must be between 0 and " + (width()-1));

if (y < 0 || y >= height()) throw new IndexOutOfBoundsException("y must be between 0 and " + (height()-1));

if (isOriginUpperLeft) return new Color(image.getRGB(x, y));

else return new Color(image.getRGB(x, height - y - 1));

}

   /**

   * Sets the color of pixel (<em>x</em>, <em>y</em>) to given color.

   */

public void set(int x, int y, Color color) {

if (x < 0 || x >= width()) throw new IndexOutOfBoundsException("x must be between 0 and " + (width()-1));

if (y < 0 || y >= height()) throw new IndexOutOfBoundsException("y must be between 0 and " + (height()-1));

if (color == null) throw new NullPointerException("can't set Color to null");

if (isOriginUpperLeft) image.setRGB(x, y, color.getRGB());

else image.setRGB(x, height - y - 1, color.getRGB());

}

   /**

   * Is this Picture equal to obj?

   */

public boolean equals(Object obj) {

if (obj == this) return true;

if (obj == null) return false;

if (obj.getClass() != this.getClass()) return false;

Picture that = (Picture) obj;

if (this.width() != that.width()) return false;

if (this.height() != that.height()) return false;

for (int x = 0; x < width(); x++)

for (int y = 0; y < height(); y++)

if (!this.get(x, y).equals(that.get(x, y))) return false;

return true;

}

   /**

   * Saves the picture to a file in a standard image format.

   * The filetype must be .png or .jpg.

   */

public void save(String name) {

save(new File(name));

}

   /**

   * Saves the picture to a file in a standard image format.

   */

public void save(File file) {

this.filename = file.getName();

if (frame != null) { frame.setTitle(filename); }

String suffix = filename.substring(filename.lastIndexOf('.') + 1);

suffix = suffix.toLowerCase();

if (suffix.equals("jpg") || suffix.equals("png")) {

try { ImageIO.write(image, suffix, file); }

catch (IOException e) { e.printStackTrace(); }

}

else {

System.out.println("Error: filename must end in .jpg or .png");

}

}

   /**

   * Opens a save dialog box when the user selects "Save As" from the menu.

   */

public void actionPerformed(ActionEvent e) {

FileDialog chooser = new FileDialog(frame,

   "Use a .png or .jpg extension", FileDialog.SAVE);

chooser.setVisible(true);

if (chooser.getFile() != null) {

save(chooser.getDirectory() + File.separator + chooser.getFile());

}

}

Solutions

Expert Solution

public int countConnectedBlocks(Picture picture) {
    if (picture.length == 0) {
      return 0;
    }
    int blobCount = 0;
    visited = new boolean[picture.length][picture[0].length];
    for (int i = 0; i < picture.length; i++) {
      for (int j = 0; j < picture[i].length; j++) {
        if (!visited[i][j]) {
          if (isBlack(i, j)) {
            countHelper(i, j);
            blobCount++;
          }
          visited[i][j] = true;
        }
      }
    }
    return blobCount;
  }

  private void countHelper(int i, int j) {
    visited[i][j] = true;
    if (isBlack(i, j)) {
      for (int deltaI = -1; deltaI <= 1; deltaI++) {
        for (int deltaJ = -1; deltaJ <= 1; deltaJ++) {
          int adjI = i + deltaI;
          int adjJ = j + deltaJ;
          if (inBounds(adjI, adjJ) && !visited[adjI][adjJ]) {
            countHelper(adjI, adjJ);
          }
        }
      }
    }
  }

  private boolean inBounds(int i, int j) {
    return i >= 0 && j >= 0 && i < picture.length && j < picture[i].length;
  }

Related Solutions

Using the following in Java- package intersectionprinter; import java.awt.Rectangle; public class IntersectionPrinter { public static void...
Using the following in Java- package intersectionprinter; import java.awt.Rectangle; public class IntersectionPrinter { public static void main(String[] args) { Rectangle r1 = new Rectangle(0,0,100,150); System.out.println(r1);    Rectangle r2 = new Rectangle(50,75,100,150); System.out.println(r2);    Rectangle r3 = r1.intersection(r2);    } } Write a program that takes both Rectangle objects, and uses the intersection method to determine if they overlap. If they do overlap, then print it's coordinates along with its width and height. If there is no intersection, then have the...
Determine the Output: Package questions; import java.util.*; public class Quiz1 {       public static void main(String[] args)...
Determine the Output: Package questions; import java.util.*; public class Quiz1 {       public static void main(String[] args) {             // TODO Auto-generated method stub             System.out.println("*** 1 ***");             ArrayList<Integer>list1=new ArrayList<Integer>();             for(int i=0;i<30;i++)             {                   list1.add(new Integer(i));             }             System.out.print("[");             for(int i=0;i<list1.size();i++)             {                   System.out.print(list1.get(i)+" ");             }             System.out.println("]");                           System.out.println("*** 2 ***");             ArrayList<Integer>list2=new ArrayList<Integer>();             for(int i=30;i<60;i++)             {                   list2.add(i); //Auto Boxing an Integer not need to use new Integer             }             System.out.println(list2); //toString for an ArrayList --created by the Java Programmers                           System.out.println("*** 3 ***");             ArrayList<Integer>list3=new ArrayList<Integer>();             list3.add(list1.remove(22)); //when...
import java.util.*; import java.security.*; import javax.crypto.*; import java.nio.file.*; public class CryptoApp {    public static void...
import java.util.*; import java.security.*; import javax.crypto.*; import java.nio.file.*; public class CryptoApp {    public static void main(String[] args) throws Exception { Crypto crypto = new BasicCrypto();        String welcome = "Hello 2043-er's! Let's try this again :-)"; System.out.println(welcome); // First, where are we? //Let's print out our current working directory        Path cwd = FileSystems.getDefault().getPath("").toAbsolutePath(); System.out.println("Current Working Directory: " + cwd); // Read in our file to encrypt    byte[] originalData = Files.readAllBytes(Paths.get(System.getProperty("user.home"), "C-2044-Sample/Crypto/src/encrypt.txt")); // Encrypt it and...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class Main { static Scanner sc=new Scanner(System.in);...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class Main { static Scanner sc=new Scanner(System.in); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static void main(String[] args) throws IOException { // TODO code application logic here System.out.print("Enter any String: "); String str = br.readLine(); System.out.print("\nEnter the Key: "); int key = sc.nextInt(); String encrypted = encrypt(str, key); System.out.println("\nEncrypted String is: " +encrypted); String decrypted = decrypt(encrypted, key); System.out.println("\nDecrypted String is: " +decrypted); System.out.println("\n"); } public static String encrypt(String str,...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Exercise { public static void main(String[] args) {...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Exercise { public static void main(String[] args) { Scanner input=new Scanner(System.in); int[] WordsCharsLetters = {0,1,2}; while(input.hasNext()) { String sentence=input.nextLine(); if(sentence!=null&&sentence.length()>0){ WordsCharsLetters[0] += calculateAndPrintChars(sentence)[0]; WordsCharsLetters[1] += calculateAndPrintChars(sentence)[1]; WordsCharsLetters[2] += calculateAndPrintChars(sentence)[2]; } else break; } input.close(); System.out.println("Words: " + WordsCharsLetters[0]); System.out.println("Characters: " + WordsCharsLetters[1]); System.out.println("Letters: " + WordsCharsLetters[2]); } static int[] calculateAndPrintChars(String sentence) { int[] WCL = new int[3]; String[] sentenceArray=sentence.split(" "); WCL[0] = sentenceArray.length; int letterCount=0; for(int i=0;i<sentence.length();i++) { if(Character.isLetter(sentence.charAt(i))) letterCount++; } WCL[1]...
import java.util.Scanner; public class Squaring { public static void main(String[] args) { Scanner sc = new...
import java.util.Scanner; public class Squaring { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num=0; String s = ""; while (true) { System.out.println("Enter an integer greater than 1: "); try { // reading input s = sc.nextLine(); // converting into int num = Integer.parseInt(s); break; } catch (Exception e) { System.out.println(s + " is not valid input."); } } // Now we have a valid number // putting into square int square = num; int count...
import java.util.Scanner; public class ZombieApocalypse{    public static void main(String[] args){    Scanner input = new...
import java.util.Scanner; public class ZombieApocalypse{    public static void main(String[] args){    Scanner input = new Scanner(System.in);           boolean gameOver = false; int colSize = 10; int rowSize= 10; String floorTile= "."; int playerX = 0; int playerY= 0; String playerTile="@"; int exitX= colSize-1; int exitY= rowSize-1; String exitTile="# "; int zombieX=5; int zombieY=5; // Defining Second Zombie int zombie2Y= 8; int zombie2X= 3; // Defining third zombie int zombie3Y= 1; int zombie3X= 7; String zombieTile="*"; String zombie2Tile="*";...
import java.util.Scanner; public class Grade { public static void main(String[] args) { Scanner scnr = new...
import java.util.Scanner; public class Grade { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); // Reading score from user System.out.println("Enter the student's score:"); double score = scnr.nextDouble(); System.out.print("Grade:"); // Checking if score is less than 60 if(score<60){ System.out.println("F"); } // Checking if score is less than 70 else if(score<70){ System.out.println("D"); } // Checking if score is less than 80 else if(score<80){ System.out.println("C"); } // Checking if score is less than 90 else if(score<90){ System.out.println("B"); } // Checking...
import java.util.LinkedList; public class StudentLinkedList { public static void main(String[] args) { LinkedList<Student> linkedlist = new...
import java.util.LinkedList; public class StudentLinkedList { public static void main(String[] args) { LinkedList<Student> linkedlist = new LinkedList<Student>(); linkedlist.add(new Student("Ahmed Ali", 20111021, 18, 38, 38)); linkedlist.add(new Student("Sami Kamal", 20121021, 17, 39, 35)); linkedlist.add(new Student("Salem Salim", 20131021, 20, 40, 40)); linkedlist.add(new Student("Rami Mohammed", 20111031, 15, 35, 30)); linkedlist.add(new Student("Kim Joe", 20121024, 12, 32, 32)); linkedlist.addFirst(new Student("Hadi Ali", 20111025, 19, 38, 39)); linkedlist.addLast(new Student("Waleed Salim", 20131025, 10, 30, 30)); linkedlist.set(0, new Student("Khalid Ali", 20111027, 15, 30, 30)); linkedlist.removeFirst(); linkedlist.removeLast(); linkedlist.add(0, new Student("John Don",...
Java Starter Code: import java.util.Scanner; public class GameScore { static Scanner keyboard = new Scanner(System.in); public...
Java Starter Code: import java.util.Scanner; public class GameScore { static Scanner keyboard = new Scanner(System.in); public static void main(String[] args) { int team1[] = new int[4]; int team2[] = new int[4]; for (int qtr = 0; qtr < 4; qtr++) { quarterScoring(team1, team2, qtr); } int team1Total = teamTotal(team1); int team2Total = teamTotal(team2); displayGameResults(team1, team2); if (team1Total > team2Total) { System.out.println("Team 1 has won the game!"); } else { System.out.println("Team 2 has won the game!"); } } static int teamTotal(int[]...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT