Question

In: Computer Science

from PIL import Image def stringToBits(string):     return str(bin(int.from_bytes(string.encode(), 'big')))[2:] def bitsToString(bits):     if bits[0:2] != '0b':         bits.

from PIL import Image

def stringToBits(string):

    return str(bin(int.from_bytes(string.encode(), 'big')))[2:]

def bitsToString(bits):

    if bits[0:2] != '0b':

        bits = '0b' + bits

    value = int(bits, 2)

    return value.to_bytes((value.bit_length() + 7) // 8, 'big').decode()

def writeMessageToRedChannel(file, message):

    image = Image.open(file)

    width, height = image.size

    messageBits = stringToBits(message)

    messageBitCounter = 0

    y = 0

    while y < height:

        x = 0

        while x < width:

            r, g, b, a = image.getpixel((x, y))

            print("writeMessageToRedChannel: Reading pixel %d, %d - Original values (%d, %d, %d, %d)" % (x, y, r, g, b, a))

            if(messageBitCounter < len(messageBits)):

                r = int(messageBits[messageBitCounter])

            else:

                r = 255

            print("writeMessageToRedChannel: Editing pixel %d, %d - New values (%d, %d, %d, %d)" % (x, y, r, g, b, a))

            image.putpixel((x,y), (r, g, b, a))

            x += 1

            messageBitCounter += 1

        y += 1

    image.save(file)

def readMessageFromRedChannel(file):

    image = Image.open(file)

    width, height = image.size

    message = ""

    y = 0

    while y < height:

        x = 0

        while x < width:

            r, g, b, a = image.getpixel((x, y))

            if(r != 255):

                message += str(r)

            else:

                return bitsToString(message)

            x += 1

        y += 1

#########################################

### EDIT CODE BELOW THIS COMMENT ########

#########################################

def resetImage(file):

    # Open the Image specified in file

    

    # Get the width and height

    

    # Write a nested loop statement to access each pixel

    

    

        

        

            # Get the current pixel RGBA

            

            # Print the current value to the screen

            

            # Write new RGBA of (255, 255, 255, 255) to the pixel

            

            # Print the new value to the screen

            

            

        

    # Save the image file

    

#########################################

### EDIT CODE ABOVE THIS COMMENT ########

#########################################

message  = "Hello, there! How are you! I want to tell you a secret... "

message += "and the secret is that I am Batman!!!"

# Reset the image to all white pixels

# RGBA = (255, 255, 255, 255)

resetImage("secret_image.png")

# Write message to the image

print("Writing the secret message: %s" % message)

writeMessageToRedChannel("secret_image.png", message)

# Read message from the image (if it worked properly, the

# message should be the same as the one written to the image)

print("Reading the secret message: %s" % readMessageFromRedChannel("secret_image.png"))

I need help with the missing code please.

Solutions

Expert Solution

Input:

Input image

Program:

Output:

Summary:

The program is to reset the image pixels to white.

Input: Image from the user

Step:

1)Open the image file.

2) Get the width and height of the image using image.size

3) Convert the image to RBGA image (some images can be RGB)

4) Iterate through each pixel .

1)Get the current rgba using image.getpixel((row,col))

2)Print current value to the screen

3)Write new rgba to the pixel using image.putpixel((row,col),(255,255,255,255)) => white

4)Print the new value to screen

5) Save image


Related Solutions

public static char mostFrequent(String str) {        if(str.length()==0) {            return '0';   ...
public static char mostFrequent(String str) {        if(str.length()==0) {            return '0';        }        String temp="";        for (int i = 0; i < str.length(); i++) {                 if(!temp.contains(String.valueOf(str.charAt(i)))) {                     temp += String.valueOf(str.charAt(i));                 }             }        char[] tempArray=stringToArray(temp);        int[] countArr=new int[tempArray.length];        int max=0;        for(int i=0;i<tempArray.length;i++) {            int cnt=numOccurences(tempArray[i],str);            countArr[i]=cnt;...
class employee: name = str('')    hourlyWage=0 hoursWorked=0 def getPayment(self): payment=self.hourlyWage*self.hoursWorked return payment    class payrollApp(employee):...
class employee: name = str('')    hourlyWage=0 hoursWorked=0 def getPayment(self): payment=self.hourlyWage*self.hoursWorked return payment    class payrollApp(employee):    def printStatement(self): print('The Employee Name is ' + self.name) print('The Employee Hourly wage is ' + str(self.hourlyWage)) print('No of hours worked ' + str(self.hoursWorked)) print('The Employee payment is ' + str(employee.getPayment(self))) emp = [] x=0 a=True totalPayout=0 while a:    emp.append(payrollApp()) emp[x].name=input("Enter Employee Name: ") emp[x].hourlyWage=int(input("Enter hourly wage: ")) emp[x].hoursWorked=int(input("Enter No of hours worked: ")) totalPayout= totalPayout + (emp[x].hourlyWage * emp[x].hoursWorked) print("\n") x=x+1...
Assume that bits is a string that only contains the characters "0" and "1". n is...
Assume that bits is a string that only contains the characters "0" and "1". n is an integer variable that is less than the length of bits. Fill in the blanks below to replace bits with a new string that consists of all of the characters of bits from index n through the end, followed by the first n characters of bits. For example, if bits was "1101010" and n was 3, the new value of bits would be "1010110"....
def annoying_factorial(n): if n == 0 or n == 1: return 1 if n == 2:...
def annoying_factorial(n): if n == 0 or n == 1: return 1 if n == 2: return 2 if n == 3: return 6 if n == 4: return 4 * annoying_factorial(3) if n == 5: return 5 * annoying_factorial(4) if n == 6: return 6 * annoying_factorial(5) else: return n * annoying_factorial(n-1) def annoying_fibonacci(n): if n==0: return 0 if n==1: return 1 if n==2: return 1 if n==3: return 2 if n==4: return annoying_fibonacci(4-1)+annoying_fibonacci(4-2) if n==5: return annoying_fibonacci(5-1)+annoying_fibonacci(5-2) if...
from typing import List def longest_chain(submatrix: List[int]) -> int: """ Given a list of integers, return...
from typing import List def longest_chain(submatrix: List[int]) -> int: """ Given a list of integers, return the length of the longest chain of 1's that start from the beginning. You MUST use a while loop for this! We will check. >>> longest_chain([1, 1, 0]) 2 >>> longest_chain([0, 1, 1]) 0 >>> longest_chain([1, 0, 1]) 1 """ i = 0 a = [] while i < len(submatrix) and submatrix[i] != 0: a.append(submatrix[i]) i += 1 return sum(a) def largest_rectangle_at_position(matrix: List[List[int]], x:...
Q8. If the bits 0 and 2 of P1IN are set, then toggle all the bits...
Q8. If the bits 0 and 2 of P1IN are set, then toggle all the bits of P1OUT simultaneously except the bit 4, else toggle only the bit 4 of P1OUT.
import random import turtle def isInScreen(win,turt): leftBound = -win.window_width() / 2 rightBound = win.window_width() / 2...
import random import turtle def isInScreen(win,turt): leftBound = -win.window_width() / 2 rightBound = win.window_width() / 2 topBound = win.window_height() / 2 bottomBound = -win.window_height() / 2 turtleX = turt.xcor() turtleY = turt.ycor() stillIn = True if turtleX > rightBound or turtleX < leftBound: stillIn = False if turtleY > topBound or turtleY < bottomBound: stillIn = False return stillIn def main(): wn = turtle.Screen() # Define your turtles here june = turtle.Turtle() june.shape('turtle') while isInScreen(wn,june): coin = random.randrange(0, 2) if...
import Stack def stack_mystery(myStack):      mystery=0     while not myStack.isEmpty():          value=myStack.pop()          if v
import Stack def stack_mystery(myStack):      mystery=0     while not myStack.isEmpty():          value=myStack.pop()          if value> mystery:              mystery=value                return mystery def main():    s=Stack.Stack()        s.push(20)        s.push(10)        s.push(50)        s.push(100)        s.push(40)        print(stack_mystery(s)) main() Answer the following questions a) What is the output of the print(stack_mystery(s)) statement in the main method? b) What is the task of the stack_mystery function? What does the mystery variable represent?
def warmer_year(temps_then: List[int], temps_now: List[int]) -> List[str]: """Return a list of strings representing whether this year's...
def warmer_year(temps_then: List[int], temps_now: List[int]) -> List[str]: """Return a list of strings representing whether this year's temperatures from temps_now are warmer than past temperatures in temps_then. The resulting list should contain "Warmer" at the indexes where this year's temperature is warmer, and "Not Warmer" at the indexes where the past year was warmer, or there is a tie. Precondition: len(temps_then) == len(temps_now) >>> warmer_year([10], [11]) ['Warmer'] >>> warmer_year([26, 27, 27, 28], [25, 28, 27, 30]) ['Not Warmer', 'Warmer', 'Not Warmer',...
import java.util.Scanner; public class LetterGrade { // The method you write will return a String representing...
import java.util.Scanner; public class LetterGrade { // The method you write will return a String representing a letter // grade (e.g., "A", "A-", "B+", etc.). // The letter grade is determined by the given percentage, according // to the scale specified on page 2 of the class syllabus (available // here: https://kyledewey.github.io/comp110-spring18/syllabus.pdf). // You may assume that the given percentage is between 0.0 and 100.0 // TODO - write your code below this comment.    public static String letterGrade(double percentage){...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT