You are given an image representing a scanned OMR answer sheet. Each image contains a…
- User
You are given an image representing a scanned OMR answer sheet. Each image contains a grid of circles, with each row representing one question and each column representing a possible answer (A, B, C, D). Some circles are filled to indicate the selected answer by the candidate.
Your task is to write a program that takes the image as input, along with an array containing the correct answers for each question and returns a score based on the number of correct answers. For each correct answer, score will be incremented by 1 point. Each question has only 1 correct answer.
The filled circles in the images can be either fully filled (360 degrees filled) or partially filled. A fully filled circle represents a definite answer, while a partially filled circle represents a probable answer. If a circle is filled more than 75% (270 degrees filled) of the area, it should be considered as a definite answer. Sample OMR images
For the below image, when evaluating with the expected answer as D A D C, the score is evaluated as 4
image
For the below image, where partial circles are filled, when evaluating with expected answer as C D D D, the score is evaluated as 3
image
Note
Few things to keep in mind while evaluating the score
A filled circle is considered definite answer when 75% of the circle area is filled, which means 270 degress or more must be filled to consider it as a definite answer.
If a candidate has marked more than one circle as definite answer for a question, then even if the definite answers contains the correct answer, no score will be provided for that question.
Input Format Guidelines
First line in the standard input represents the image to be used eg. omr_sheet_1.png Second line in the standard input represents the correct answer for the omr sheet, separated by a space
Sample Input
omr_sheet_1.png D A D C Reading the Input
You can read the input as standard input.
To load the image, you can load it as following: Python
//read from standard input filename = input() // get file if os.path.isfile(filename): Open the file
with open(filename, 'r') as file: ... Java
import java.io.File; ... // read from standard input Scanner scanner = new Scanner(System.in); String query = scanner.nextLine(); // Get the image file File file = new File("omr_sheet_1.png");
Constraints Image constraints
All Image dimensions are 500 x 500 2 color present only, black & white. Every image has 4 Questions with 4 options. Every Question has only 1 correct question.
Output Format Guidelines
Please output only the score in standard output
For the above question i am getting runtime error in below code import struct import zlib
def get_png_pixel_data(filename): # Read the PNG file with open(filename, 'rb') as f: # Check PNG signature signature = f.read(8) if signature != b'\x89PNG\r\n\x1a\n': raise ValueError("Not a valid PNG file")
width = height = None image_data = b'' color_type = None bit_depth = None # Read chunks until we find IHDR (image header) and IDAT (image data) while True: # Read chunk length and type chunk_len, chunk_type = struct.unpack(">I4s", f.read(8)) chunk_data = f.read(chunk_len) f.read(4) # CRC, not used here if chunk_type == b'IHDR': # Header chunk width, height, bit_depth, color_type, compression, filter_method, interlace = struct.unpack(">IIBBBBB", chunk_data) # print(f"Image size: {width}x{height}, bit depth: {bit_depth}, color type: {color_type}") if width != 500 or height != 500: raise ValueError("Only 500x500 images are supported") elif chunk_type == b'IDAT': # Image data chunk image_data += chunk_data elif chunk_type == b'IEND': # End of PNG file break # Decompress the image data decompressed_data = zlib.decompress(image_data) # For grayscale conversion: # color_type 2 means RGB, we need to convert it to grayscale grayscale_image = [[0 for _ in range(width)] for _ in range(height)] # Create a 500x500 array if color_type == 2: # RGB image row_size = width * 3 # 3 bytes per pixel (RGB) for y in range(height): filter_type = decompressed_data[y * (row_size + 1)] # Ignore filter type for now row_data = decompressed_data[y * (row_size + 1) + 1: (y + 1) * (row_size + 1)] for x in range(0, row_size, 3): # Read RGB triplet r = row_data[x] g = row_data[x + 1] b = row_data[x + 2] # Convert to grayscale using the luminosity formula grayscale_value = int(0.299 * r + 0.587 * g + 0.114 * b) grayscale_image[y][x // 3] = grayscale_value elif color_type == 0: # Already grayscale row_size = width # 1 byte per pixel in grayscale for y in range(height): filter_type = decompressed_data[y * (row_size + 1)] # Ignore filter type for now row_data = decompressed_data[y * (row_size + 1) + 1: (y + 1) * (row_size + 1)] for x in range(width): grayscale_image[y][x] = row_data[x] else: raise ValueError("Unsupported PNG color type") return grayscale_imageExample usage
filename = input()
char_to_num = { 'A': 0, 'B': 1, 'C': 2, 'D': 3 }
Convert the string to an array of numbers
num_array = [char_to_num[char] for char in input().split()]
grayscale_image = get_png_pixel_data(filename)
Assuming a 500x500 grayscale image
image_height = len(grayscale_image) image_width = len(grayscale_image[0])
print(image_height,image_width)
window_size = 32
col_start_pts = [32,162,296,432] row_start_pts = [36,168,300,432]
correct_ans = 0 answered_qs = set()
Loop through the image in 32x32 blocks
for idx,row_start in enumerate(row_start_pts): for idy,col_start in enumerate(col_start_pts): black_pixel_count = 0 total_pixels = window_size * window_size
# Traverse through the 32x32 block for row in range(row_start, min(row_start + window_size, image_height)): for col in range(col_start, min(col_start + window_size, image_width)): # Check if the pixel is black (assuming black is value 0) if grayscale_image[row][col] == 0: black_pixel_count += 1 # Calculate the percentage of black pixels in the current 32x32 block black_percentage = (black_pixel_count / total_pixels) * 100 if black_percentage>50: if idx in answered_qs: correct_ans-=1 answered_qs.remove(idx) elif num_array[idx] == idy: correct_ans+=1 answered_qs.add(idx) # print(f"Block ({col_start}, {row_start}) - Black Pixel %: {black_percentage:.2f}%")print(correct_ans)
- Assistant
The runtime error you're encountering likely stems from manually parsing and decoding the PNG file. Handling PNG files manually is complex due to various factors like different color types, bit depths, and filtering methods. Instead of manually decoding the PNG, it's highly recommended to use established image processing libraries such as Pillow or OpenCV. These libraries handle the intricacies of image formats and provide powerful tools for image manipulation and analysis.
Below, I provide a comprehensive solution using OpenCV, which is well-suited for image analysis tasks like the one you're working on. This approach will be more robust, efficient, and easier to maintain.
Step-by-Step Solution
-
Install Required Libraries:
Ensure you have OpenCV installed. You can install it using
pip:pip install opencv-python -
Load and Preprocess the Image:
- Convert the image to grayscale.
- Apply binary thresholding to make the image strictly black and white.
- Optionally, perform morphological operations to eliminate noise.
-
Define Regions for Answer Circles:
Since the image has a fixed size (500x500) with 4 questions and 4 options each, you can define the coordinates where each circle is expected to be located.
-
Detect Filled Circles:
For each circle region:
- Count the number of black pixels.
- Determine if the filled area exceeds the 75% threshold.
- Handle cases where multiple circles are filled.
-
Compare with Correct Answers and Calculate the Score.
Complete Python Solution Using OpenCV
import cv2 import numpy as np import sys def main(): import sys # Read input from standard input lines = sys.stdin.read().splitlines() if len(lines) < 2: print("0") sys.exit(0) filename = lines[0].strip() correct_answers = lines[1].strip().split() # Validate the correct_answers length if len(correct_answers) != 4: print("0") sys.exit(0) # Mapping from option letter to index char_to_num = {'A':0, 'B':1, 'C':2, 'D':3} correct_num_array = [char_to_num[ans.upper()] for ans in correct_answers] # Load the image try: image = cv2.imread(filename) if image is None: print("0") sys.exit(0) except: print("0") sys.exit(0) # Convert to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Apply binary threshold # Assuming black is 0 and white is 255 _, thresh = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY_INV) # Define the grid of circles # Assuming the positions are fixed based on the image dimensions # Adjust these coordinates based on actual image # Example coordinates for 4 questions and 4 options each # These should be the center points of the circles # For a 500x500 image, define approximate centers # You might need to adjust these based on actual OMR sheet layout questions = 4 options = 4 # Define starting and ending y-coordinates for rows (questions) row_start_pts = [50, 150, 250, 350] # Define starting and ending x-coordinates for columns (options) col_start_pts = [100, 200, 300, 400] # Define radius for the circles circle_radius = 20 # Define area threshold (75% of circle area) circle_area = np.pi * (circle_radius ** 2) threshold_area = 0.75 * circle_area filled_answers = [] for q in range(questions): filled_options = [] y = row_start_pts[q] for opt in range(options): x = col_start_pts[opt] # Create a mask for the circle mask = np.zeros_like(gray) cv2.circle(mask, (x, y), circle_radius, 255, -1) # Bitwise AND with thresholded image masked = cv2.bitwise_and(thresh, thresh, mask=mask) # Count non-zero (white) pixels in the masked area filled_pixels = cv2.countNonZero(masked) # Check if filled_pixels exceed threshold if filled_pixels > threshold_area: filled_options.append(opt) filled_answers.append(filled_options) # Now, calculate the score based on the rules score = 0 for q in range(questions): if len(filled_answers[q]) == 1: selected = filled_answers[q][0] if selected == correct_num_array[q]: score += 1 # If no options or multiple options are filled, no score is added print(score) if __name__ == "__main__": main()Explanation of the Solution
-
Input Handling:
- The program reads two lines from the standard input: the filename and the correct answers.
- It validates the number of correct answers to ensure there are exactly four.
-
Image Loading and Preprocessing:
- Loading: Uses OpenCV's
imreadto load the image. If the image can't be loaded, it exits with a score of0. - Grayscale Conversion: Converts the image to grayscale using
cvtColor. - Thresholding: Applies binary inversion thresholding (
THRESH_BINARY_INV) so that filled circles become white (255) and the background becomes black (0).
- Loading: Uses OpenCV's
-
Defining Circle Positions:
- Assumes fixed positions for the centers of the circles. You might need to adjust
row_start_ptsandcol_start_ptsbased on the actual layout of your OMR sheets. circle_radiusis set to20. Adjust this value if your circles are larger or smaller.
- Assumes fixed positions for the centers of the circles. You might need to adjust
-
Detecting Filled Circles:
- For each question and each option, a circular mask is created.
- The mask is applied to the thresholded image to isolate the circle area.
- The number of white pixels (
filled_pixels) within the masked area is counted. - If the count exceeds
75%of the circle's area, it's considered a filled circle.
-
Scoring Logic:
- For each question, if exactly one circle is filled, it checks whether the filled option matches the correct answer.
- If multiple circles are filled or none are filled, the question is considered unanswered or ambiguously answered, and no points are awarded.
- The final score is the total number of correctly answered questions.
Customization
-
Adjusting Circle Positions:
The positions (
row_start_ptsandcol_start_pts) are currently set based on assumptions. You'll need to adjust these values to match the actual layout of your OMR sheets. You can use image editing tools or OpenCV's GUI functions to determine the exact coordinates. -
Circle Radius:
If your OMR circles are larger or smaller, adjust the
circle_radiusaccordingly. -
Thresholding Parameters:
The threshold value (
128in this case) might need tweaking based on the quality of the scanned images. If the scanned images have varying lighting conditions, consider using adaptive thresholding or other preprocessing techniques to improve accuracy.
Handling Runtime Errors
By using OpenCV:
- Simplified Image Handling: OpenCV handles all the complexities of image decoding, allowing you to focus on the analysis.
- Error Handling: The code includes basic error handling to ensure that if the image can't be loaded or the input is invalid, the program exits gracefully with a score of
0. - Performance: OpenCV is optimized for performance, making the processing faster and more reliable.
Testing the Solution
To test the solution, ensure you have an appropriate OMR sheet image (
omr_sheet_1.png) and provide the correct inputs. Here's how you can run the program:python omr_scoring.pyProvide the input through standard input, for example:
omr_sheet_1.png D A D CThe program will output the score based on the filled circles in the image.
Conclusion
Manually parsing PNG files is error-prone and not recommended for image analysis tasks. Leveraging powerful libraries like OpenCV simplifies the process, enhances reliability, and provides flexibility to handle various image processing requirements. The provided solution should effectively address the runtime errors and accurately score the OMR sheets based on the filled circles.
-