I am working with a 16 bit DICOM Image whose size is 512*512. I want to draw a rectangle at 250,375 positions with length and width 50,50 respectively. I am capable to draw rectangle on that particular position. But, I am incapable to save the image with the rectangle. Is it possible to write the image with rectangle. I=dicomread('F:\img1.dcm'); figure,imshow(X, []); hold on; title('16 bit image.', 'FontSize', 10); rectangle('Position', [250,375,100,100],... 'EdgeColor','r', 'LineWidth', 3); imwrite(X,'C:\Users\Jhilam\Desktop\code\myfile.png','WriteMode','append');
John Michell answered .
2025-11-20
To write a 16-bit image with a drawing (e.g., a rectangle) into a folder, you can follow these steps in Python or MATLAB:
Here’s an example:
import cv2
import numpy as np
import os
# Step 1: Create a 16-bit grayscale image (e.g., 512x512 pixels)
image = np.zeros((512, 512), dtype=np.uint16)
# Step 2: Draw a white rectangle on the image
top_left = (100, 100) # Top-left corner of the rectangle
bottom_right = (300, 300) # Bottom-right corner of the rectangle
color = 65535 # Maximum intensity for 16-bit image
thickness = 5 # Thickness of the rectangle border
cv2.rectangle(image, top_left, bottom_right, color, thickness)
# Step 3: Define the folder and file path
output_folder = "output_images"
os.makedirs(output_folder, exist_ok=True) # Create folder if it doesn't exist
output_path = os.path.join(output_folder, "image_with_rectangle.tiff")
# Step 4: Save the image in 16-bit format
cv2.imwrite(output_path, image)
print(f"Image saved at {output_path}")
rectangle function to define and draw the rectangle.Here’s an example:
% Step 1: Create a 16-bit grayscale image
image = uint16(zeros(512, 512)); % 512x512 pixels, 16-bit
% Step 2: Define and draw a rectangle
top_left = [100, 100]; % Top-left corner
width = 200; % Width of the rectangle
height = 200; % Height of the rectangle
% Draw the rectangle by modifying pixel values
image(top_left(2):top_left(2)+height, top_left(1):top_left(1)+width) = 65535;
% Step 3: Save the image to a folder
output_folder = 'output_images';
if ~exist(output_folder, 'dir')
mkdir(output_folder); % Create folder if it doesn't exist
end
output_path = fullfile(output_folder, 'image_with_rectangle.tiff');
% Step 4: Write the image to the file
imwrite(image, output_path);
disp(['Image saved at ', output_path]);