|
|
| """
|
| Created on Tue Dec 10 09:15:10 2024
|
|
|
| This code calculates the edge density of an image in blocks. It uses Canny edge detection to identify edges and calculates
|
| the percentage of edge pixels in each block. The results can be used to analyze features such as wrinkles on fruit surfaces.
|
|
|
| @author: jishu
|
| """
|
|
|
| import cv2
|
| import numpy as np
|
|
|
| def calculate_edge_density(image, block_size=(50, 50)):
|
| """
|
| Calculates edge density in blocks for a given image.
|
|
|
| Parameters:
|
| image_path (str): Path to the input image.
|
| block_size (tuple): Dimensions of the blocks (height, width).
|
|
|
| Returns:
|
| list: Edge densities for each block (in percentage).
|
| """
|
|
|
| if image is None:
|
| print("Error: Image not found!")
|
| return None
|
|
|
|
|
| resized_image = cv2.resize(image, (512, 512))
|
|
|
|
|
| blurred = cv2.GaussianBlur(resized_image, (5, 5), 0)
|
|
|
|
|
| edges = cv2.Canny(blurred, threshold1=50, threshold2=100)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| densities = []
|
| height, width = edges.shape
|
| block_height, block_width = block_size
|
|
|
|
|
| for y in range(0, height, block_height):
|
| for x in range(0, width, block_width):
|
|
|
| block = edges[y:y+block_height, x:x+block_width]
|
|
|
|
|
| block = block[:block_height, :block_width]
|
|
|
|
|
| edge_pixels = np.sum(block == 255)
|
| total_pixels = block.size
|
| density = (edge_pixels / total_pixels) * 100
|
| densities.append(density)
|
|
|
| return np.mean(np.array(densities))
|
|
|
|
|
|
|