Question

the following python code edits BMP image file to negative but I need help with modifying...

the following python code edits BMP image file to negative but I need help with modifying this code so it turns it the same BMP image file into a black and white instead of a negative. heres python code I have so far [pasted below]

##

# This program processes a digital image by creating a negative of a BMP image.

#

from io import SEEK_CUR

from sys import exit

def main() :

filename = input("Please enter the file name: ")

# Open as a binary file for reading and writing.

imgFile = open(filename, "rb+")

# Extract the image information.

fileSize = readInt(imgFile, 2)

start = readInt(imgFile, 10)

width = readInt(imgFile, 18)

height = readInt(imgFile, 22)

# Scan lines must occupy multiples of four bytes.

scanlineSize = width * 3

if scanlineSize % 4 == 0 :

padding = 0

else :

padding = 4 - scanlineSize % 4

# Make sure this is a valid image.

if fileSize != (start + (scanlineSize + padding) * height) :

sys.exit("Not a 24-bit true color image file.")

# Move to the first pixel in the image.

imgFile.seek(start)

# Process the individual pixels.

for row in range(height) : # For each scan line

for col in range(width) : # For each pixel in the line

processPixel(imgFile)

# Skip the padding at the end.

imgFile.seek(padding, SEEK_CUR)

imgFile.close()

## Processes an individual pixel.

# @param imgFile the binary file containing the BMP image

#

def processPixel(imgFile) :

# Read the pixel as individual bytes.

theBytes = imgFile.read(3)

blue = theBytes[0] 51 green = theBytes[1]

red = theBytes[2]

# Process the pixel.

newBlue = 255 - blue

newGreen = 255 - green

newRed = 255 - red

#Write the pixel.

imgFile.seek(-3, SEEK_CUR) # Go back 3 bytes to the start of the pixel.

imgFile.write(bytes([newBlue, newGreen, newRed]))

## Gets an integer from a binary file.

# @param imgFile the file

# @param offset the offset at which to read the integer

# @return the integer starting at the given offset

#

def readInt(imgFile, offset) :

# Move the file pointer to the given byte within the file.

imgFile.seek(offset)

# Read the 4 individual bytes and build an integer.

theBytes = imgFile.read(4)

result = 0

base = 1

for i in range(4) :

result = result + theBytes[i] * base

base = base * 256

return result

# Start the program.

main()

0 0
Add a comment Improve this question Transcribed image text
Answer #1
from matplotlib import pyplot as plt
import cv2
import os


# Setting Working Directory To Custom
os.chdir(os.getcwd() + r'\resources')

def image():
    # Set ImageName
    img_name = r'\2.jpg'
    # Set Image Path
    image_path = os.getcwd() + img_name
    # Load Image From Which The Faces Are To Be Detected
    image = cv2.imread(image_path,0)
    # Set Color Formatting To 'GRAY / RGB' From 'BGR'
    (thresh, im_bw) = cv2.threshold(image, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    thresh = 127
    im_bw = cv2.threshold(image, thresh, 255, cv2.THRESH_BINARY)[1]
    # rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    cv2.imwrite('bw_image.png', im_bw)
    cv2.waitKey(0)


# Start Of Main
if __name__ == '__main__':
    image()

IF YOU HAVE ANY QUERY, KINDLY FEEL FREE TO ASK. AND LEAVE A THUMBS UP! THANKS!

Add a comment
Know the answer?
Add Answer to:
the following python code edits BMP image file to negative but I need help with modifying...
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
  • Python Project

    AssignmentBitmap files map three 8-bit (1-byte) color channels per pixel. A pixel is a light-emitting "dot" on your screen. Whenever you buy a new monitor, you will see the pixel configuration by its width and height, such as 1920 x 1080 (1080p) or 3840x2160 (4K). This tells us that we have 1080 rows (height), and each row has 1920 (width) pixels.The bitmap file format is fairly straight forward where we tell the file what our width and height are. When...

  • Encoding and Decoding PPM image 3 & 4 are parts of question 2 Code for a09q1:...

    Encoding and Decoding PPM image 3 & 4 are parts of question 2 Code for a09q1: We were unable to transcribe this image3 Encoding an Image in a09q2.py In the next four sections, you will no longer write class methods but rather functions. In each of the next four parts, you should be importing the PPM class from a09q1.py to use with the command from a09q1 import PPM Note that this is similar to how the check module was imported...

  • Assignment Λ You shall write a Java program that accepts 5 command-line arguments and generates an image of a Sierpinski triangle, as a 24- bit RGB PNG image file. Specifications The command-line arg...

    Assignment Λ You shall write a Java program that accepts 5 command-line arguments and generates an image of a Sierpinski triangle, as a 24- bit RGB PNG image file. Specifications The command-line arguments shall consist of the following 1. The width (in pixels) of the image, as a positive decimal integer 2. The height (in pixels) of the image, as a positive decimal integer 3. The minimum area (in pixels) that a triangle must have in order to be drawn,...

  • Hi. I require your wonderful help with figuring out this challenging code. import java.awt.Color; import java.awt.image.BufferedImage;...

    Hi. I require your wonderful help with figuring out this challenging code. import java.awt.Color; import java.awt.image.BufferedImage; import java.io.*; import javax.imageio.ImageIO; public class ImageLab { /* * This is the grayscale example. Use it for inspiration / help, but you dont * need to change it. * * Creates and returns a new BufferedImage of the same size as the input * image. The new image is the grayscale version of the input (red, green, and * blue components averaged together)....

  • Mountain Paths (Part 1) Objectives 2d arrays Store Use Nested Loops Parallel data structures (i.e...

    Mountain Paths (Part 1) in C++ Objectives 2d arrays Store Use Nested Loops Parallel data structures (i.e. parallel arrays … called multiple arrays in the zyBook) Transform data Read from files Write to files structs Code Requirements Start with this code: mtnpathstart.zip Do not modify the function signatures provided. Do not #include or #include Program Flow Read the data into a 2D array Find min and max elevation to correspond to darkest and brightest color, respectively Compute the shade of...

  • could you please help me with this problem, also I need a little text so I...

    could you please help me with this problem, also I need a little text so I can understand how you solved the problem? import java.io.File; import java.util.Scanner; /** * This program lists the files in a directory specified by * the user. The user is asked to type in a directory name. * If the name entered by the user is not a directory, a * message is printed and the program ends. */ public class DirectoryList { public static...

  • I NEED HELP WITH DEBUGGING A C PROGRAM! PLEASE HEAR ME OUT AND READ THIS. I...

    I NEED HELP WITH DEBUGGING A C PROGRAM! PLEASE HEAR ME OUT AND READ THIS. I just have to explain a lot so you understand how the program should work. In C programming, write a simple program to take a text file as input and encrypt/decrypt it by reading the text bit by bit, and swap the bits if it is specified by the first line of the text file to do so (will explain below, and please let me...

  • The ACME Manufacturing Company has hired you to help automate their production assembly line. Cameras have...

    The ACME Manufacturing Company has hired you to help automate their production assembly line. Cameras have been placed above a conveyer belt to enables parts on the belt to be photographed and analyzed. You are to augment the system that has been put in place by writing C code to detect the number of parts on the belt, and the positions of each object. The process by which you will do this is called Connected Component Labeling (CCL). These positions...

  • i need help making this program the skeleton of the code is below: //Include the following #include <iostream> #...

    i need help making this program the skeleton of the code is below: //Include the following #include <iostream> #include <string> #include <fstream> //you must include this library if you wish to do file i/o using namespace std; /********************************************************* //Following is the declaration of a order record **********************************************************/ class order_record { public: string cell_number; string item_number; double quantity; double price; int processing_plant; double tax_rate; double order_tax; double net_cost; double total_cost; }; //Prototypes for your functions: input, output, and process will go...

  • i need help with a mips program to to covert roman numerals to real numbers Lab 4: Roman Numeral Conversion Part A: Due...

    i need help with a mips program to to covert roman numerals to real numbers Lab 4: Roman Numeral Conversion Part A: Due Sunday, 19 May 2019, 11:59 PM Due Friday, 24 May 2019, 11:59 PM Part B: Minimum Submission Requirements Ensure that your Lab4 folder contains the following files (note the capitalization convention): o Diagram.pdf o Lab4. asm O README.txt Commit and push your repository Lab Objective In this lab, you will develop a more detailed understanding of how...

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
ADVERTISEMENT