I have an image of a steak, and my goal is to calculate its marbling by converting the pixels to red for meat and white for fat. However, I have problems with glare in the image, which hinder the calculation. My code helps to improve it somewhat, but I would like to improve it even further. Here is an example, I have this image below, with glare:
my code is this:
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load the image
img = cv2.imread("./img.jpg")
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Apply a Gaussian filter to smooth the image
blurred = cv2.GaussianBlur(gray, (15, 15), 0)
# Calculate the difference between the original image and the smoothed one to highlight brightness
diff = cv2.absdiff(gray, blurred)
# Apply a threshold to highlight intensely bright areas
_, mask = cv2.threshold(diff, 35, 255, cv2.THRESH_BINARY)
# Invert the mask to get the dark areas (which might be glare)
mask = 255 - mask
# Apply the mask to the original image to remove glare
result = cv2.bitwise_and(img, img, mask=mask)
cv2.imwrite('marmoreio_red_5.jpg', result)
ret, data_1 = cv2.threshold(result, 127, 240, cv2.THRESH_BINARY) # Standard LG ## Various 127
cv2.imwrite("filter_1.jpeg", data_1)
# Transform non-black and non-red pixels into white
for y in range(data_1.shape[0]):
for x in range(data_1.shape[1]):
pixel = data_1[y, x]
# Define what is considered 'red' and 'black'
# (adjust these thresholds as necessary)
isRed = pixel[2] > 150 and pixel[1] < 50 and pixel[0] < 50
isBlack = pixel[2] < 50 and pixel[1] < 50 and pixel[0] < 50
if not isRed and not isBlack:
# If not red or black, set to white
pixel[0] = 255 # B
pixel[1] = 255 # G
pixel[2] = 255 # R
elif isRed:
# If it is red, standardize to the same shade of red
pixel[0] = 0 # B
pixel[1] = 0 # G
# Keep the red component as it is
elif isBlack:
# If it is black, transform to red
pixel[0] = 0 # B
pixel[1] = 0 # G
pixel[2] = 255 # R
cv2.imwrite("filter_2.jpeg", data_1)
The code helps to improve the glare, but there’s still a lot of noise. Does anyone have a tip on what I can do to improve it? Here’s the final processed image:”