Question

For this example, we are going to try and write a piece of code that counts...

For this example, we are going to try and write a piece of code that counts how many black pixels are touching a white pixel. Though this may be a contrived example, you may find the code you write to be particularly valuable when we start talking about agent based models in the next class. But for now, let's worry about the problem at hand.

How do we go about modeling this? If we consider some pixel, ?P, in our image at some coordinate [?,?][i,j] or [???,??????][row,column], whichever convention you prefer, we can look at each of the neighboring pixels that are surrounding it, ?N, by search a specific set of indices, as shown in the following diagram

We are going to write a model which looks at each pixel, ?P, and if that pixel is a black pixel, which has a value of 00, then we will check to see if any of the neighboring points, ?N, are a white pixel (which take the value 255). If so, we will count it.

Do This: The first thing we need to be cautious of is what happens when we are at the "edge" of our array. If we are in the first or last column or the first or last row, then not all of the neighboring points shown in this diagram will exist. Take for example in the pixel at index [0,0][0,0]. There is no pixel at [0−1,0][0−1,0]or [0,0−1][0,0−1] because those are "off" of the image. As a group, write a function to see whether an index is on the image or not. Some of the code has been written for you.

Finish this code
def onBoard(i, j, image):
if i <= image.shape[0]-1 and i >= 0: # You need some more conditions here!
# We've checked i, but what about j?
return True

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Consider a (4*5: 4 rows and 5 column) black and white image. So each pixel value will be either 0 (black) or 255 (white). Our code will work even if other values are there, but in the example let's take an image which has black and white pixels only.
For checking whether its touching white pixel, we have to check four pixels (left,top,right,bottom) which are adjacent to that pixel.

In this example (R0,C4), (R3,C1) these two black pixels aren't having any white pixel as a neighbour.
So total no.of black pixels which have white pixel as neighbour = 10

Code screenshot:

Code:

import numpy as np

def onBoard(i,j,image):
   if(i<=image.shape[0]-1 and i>=0 and j<=image.shape[1]-1 and j>=0):
       return True
   #else it returns False
   return False

def main():
   image = np.array([[0,255,255,0,0], [0,0,255,255,0], [255,0,0,255,255],[0,0,0,255,0]])
   row = image.shape[0]
   col = image.shape[1]
   ans = 0
   for i in range(row):
       for j in range(col):
           hit = False
           if(image[i][j]==0):   #check if the pixel is black
               #check if the position is inside board, and if it's inside check whether it's white
               if(onBoard(i,j-1,image) and image[i][j-1]==255):
                   hit = True   #if its a white, then we make 'hit=True'
               if(onBoard(i-1,j,image) and image[i-1][j]==255):
                   hit = True
               if(onBoard(i,j+1,image) and image[i][j+1]==255):
                   hit = True
               if(onBoard(i+1,j,image) and image[i+1][j]==255):
                   hit = True
               if(hit):
                   ans += 1
   print('No.of black pixel touching a white pixel',ans)

if __name__ == '__main__':
   main()

Add a comment
Know the answer?
Add Answer to:
For this example, we are going to try and write a piece of code that counts...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • WRITE A C++ PROGRAM TO ANSWER THE QUESTIONS BELOW. You are provided with an image in...

    WRITE A C++ PROGRAM TO ANSWER THE QUESTIONS BELOW. You are provided with an image in a new file format called JBC Here is an example of the format: 2 3 100 50 40 200 66 56 12 45 65 23 67 210 0 255 100 45 32 123 The first line means that this is a 2 (width) by 3 (height) image of pixels. Then, each line represents the color of a pixel. The numbers are from 0 to...

  • I need help with the edge detection code. Filter: Edge Detection Edge detection is a technique...

    I need help with the edge detection code. Filter: Edge Detection Edge detection is a technique that creates an image that looks like a pencil sketch, by changing the pixels' colours to black or white. A simple algorithm for performing edge detection is: for every pixel that has a pixel below it, check the contrast between the two pixels. If the contrast is high, change the top pixel's colour to black, but if the contrast is low, change the top...

  • Implement optimized C/C++ code using code optimization techniques Consider an image to be represented as a...

    Implement optimized C/C++ code using code optimization techniques Consider an image to be represented as a two-dimensional matrix M, where Mi,j denotes the value of M[i][j] th pixel of M. Pixel values are triples of red, green, and blue (RGB) values. We will only consider square images. Let N denote the number of rows (or columns) of an image (NxN square image). Rows and columns are numbered, in C-style, from 0 to N-1. Given this representation, the rotate operation can...

  • 4. Write a function extract(pixels, rmin, rmax, cmin, cmax) that takes the 2-D list pixels contai...

    Please design the function in version 3 of python 4. Write a function extract(pixels, rmin, rmax, cmin, cmax) that takes the 2-D list pixels containing pixels for an image, and that creates and returns a new 2-D list that represents the portion of the original image that is specified by the other four parameters. The extracted portion of the image should consist of the pixels that fall in the intersection of the rows of pixels that begin with row rmin...

  • 3 Problem 3 (10 points total) You have a set S of 220 (about a million)...

    3 Problem 3 (10 points total) You have a set S of 220 (about a million) black and white images. Each image is 30x30 pixels, and each pixel is either white or black. You want to build a dictionary that will allow you to search whether a given image is already in Part 1 (1 points): How large is the universe size U? Part 2 (9 points): You decide to use the following hash function U1...20 Pick twenty random pixels...

  • use MATLAB to upload the following: an image that you want to process (can be taken...

    use MATLAB to upload the following: an image that you want to process (can be taken yourself or downloaded from the internet) a script that processes the image in TWO ways. manipulates the colors averages pixels together Please make sure the script displays the images (like how I did with the 40 and 80 pixel averaging) so I can easily compare them to the original. Make sure to COMMENT your code as well. Homework 13 Please upload the following: an...

  • I am using Ocelot to write a program in JavaScript Our question is below: Write a...

    I am using Ocelot to write a program in JavaScript Our question is below: Write a function called removeBlueAndGreen that takes an image as an argument and returns a red version of the input image. To do so, create a copy of the input and iterate over each pixel. If the color of a pixel is (r, g, b) in the input image, its color in the output must be (r, 0.0, 0.0). Now is I write let robot =...

  • from PIL import Image import random # NOTE: Feel free to add in any constant values...

    from PIL import Image import random # NOTE: Feel free to add in any constant values you find useful to use BLACK = (0, 0, 0) WHITE = (255, 255, 255) # NOTE: Feel free to add in any helper functions to organize your code but # do NOT rename any existing functions (or else, autograder # won't be able to find them!!) # NOTE: The following function is already completed for you as an example # You can use...

  • Psuedocode works! DP is dynamic programming for this algorithm Problem 4.2. (Difficulty 3) Seam carving is...

    Psuedocode works! DP is dynamic programming for this algorithm Problem 4.2. (Difficulty 3) Seam carving is a real-world application of DP for content- aware image resizing. The simplest way to reduce the size of an image is cropping and scaling, i.e. cutting out parts of the image and scaling down the size. However, cropping leaves visible crop lines of incontinuity while scaling reduces the details of the image. We would like to intelligently reducing the size while accounting for the...

  • How do I compile c++ code in terminal. Below i have some code to apply Gaussian...

    How do I compile c++ code in terminal. Below i have some code to apply Gaussian Filter on an image using OpenCV. I have tried compling using the code g++ Project2.cpp -o Project2 `pkg-config --cflags --libs opencv` && ./Project2 and it gives me a whole list of errors saying directory not found. --------------------------------------------------------------------------------------------------------- #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <opencv2/core/core.hpp> #include <iostream> using namespace cv; using namespace std; int main() { Mat image = imread("//u//oowens//First.jpg"); int rows=image.rows; int cols=image.cols; if (image.empty())...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT