It is an image processing project that extracts a white strip with blood stain from its background image.
- demo_code.py: for explaining the algorithm**
- cropper_Swati_Kanchan.py: the actual algorithm that crops the image files stored in “data” folder.**
import numpy as np
import cv2
Importing numpy and openCV modules
img = cv2.imread('./demo_image_input.JPG')
Reading the demo image demo_image_input.JPG
ret, mask = cv2.threshold(img, 120, 255, cv2.THRESH_TOZERO)
Converting the image to a masked image using threshold of 120 and creating a black background.
rows, cols, channels = mask.shape
Getting the total number of row and column pixels and number of channels.
row_start = row_end = 0
col_mid = int(cols/2)
row_start and row_end stores the starting row pixel and ending row pixel of the white strip in the masked image.
i = rows - 1
while i >= 0:
res = np.greater_equal(mask[i, col_mid], [150, 150, 150])
if(np.array_equal(res, [True, True, True])):
row_end = i
break
i -= 20
Calculates the end row pixel of the white strip in the image.
i = 0
while i < rows:
res = np.greater_equal(mask[i, col_mid], [150, 150, 150])
if(np.array_equal(res, [True, True, True])):
row_start = i
break
i+=20
Calculates the start row pixel of the white strip in the image.
cropped = img[row_start:row_end, 0:cols]
Region of image from row_start to row_end(vertically) and 0 to cols(horizontally) is stored in cropped.
cv2.namedWindow('Cropped_Image', cv2.WINDOW_NORMAL)
cv2.namedWindow('Original_Image', cv2.WINDOW_NORMAL)
cv2.namedWindow('Masked_Image', cv2.WINDOW_NORMAL)
cv2.imshow('Original_Image', img)
cv2.imshow('Masked_Image', mask)
cv2.imshow('Cropped_Image', cropped)
Creates 3 different resizeable windows each showing all the 3 stages of the image.
cv2.waitKey(0)
cv2.destroyAllWindows()
All the windows wait for any key to be clicked and closes all the windows automatically.
cv2.imwrite('./demo_output_image.JPG', cropped)
Finally writes the cropped image into a new file named “demo_output_image.jpg”.
Resources: