Crop image center
Python Script
Crop an image to a specified size. Only the data is copied.
Preview
'''
Crop and image to specified size.
Only the data is copied.
'''
import DigitalMicrograph as DM
import numpy as np
#Find the front image, and get the image data as numpy array
image = DM.GetFrontImage()
image_data = image.GetNumArray()
#Specify Final Image Size
size_x_out = 64
size_y_out = 64
#Get input image sixe and center
sx,sy = image_data.shape
center_x = sx//2
center_y = sy//2
#Print info to Output Window
print('Current Image is %s x %s pixels' %(sx,sy))
print('Cropped Image is %s x %s pixels' %(size_x_out,size_y_out))
#Check sizes
if (size_x_out <= sx) & (size_y_out <= sy):
#Get top-left corner coordinates
x_min = center_x-size_x_out//2
y_min = center_y-size_y_out//2
#Get cropped image data
im_cropped_data = np.copy(image_data[y_min:y_min+size_y_out,x_min:x_min+size_x_out])
#Create new image from numpy array
im_cropped = DM.CreateImage(im_cropped_data)
#Set Cropped Image Name Based on Original
im_cropped.SetName("Cropped "+image.GetName())
#Display cropped image
im_cropped.ShowImage()
# Delete Py_Image variable
del im_cropped
else: print("Cropped size is larger than original image")
# Delete Py_Image variable
del image