Split/Crop 3d Image slices into 3d small objects.

Hi. I have grayscale images 720x720x300(image size where 300 slices of 3d image). To generate more examples from available data i cropped the images into multiple small objects. But i just use WxH and i need Z too. I don’t know how to do it in python. Here is the code in which i need Z too to get squared blocks. Thank You.

for dirname, _, filenames in os.walk(r'E:\E-Papers\MisData\A3d'):
    for filename in filenames:
                    imagepath=(os.path.join(dirname, filename))
                    print(imagepath)
                    if(filename=="desktop.ini"):
                        continue;
                    img = Image.open(imagepath)
                    size = img.size
                    print(size)

                    weight = int(size[0] // n)
                    height = int(size[1] // n)

                    #print(weight, height)
                    cwd = os.getcwd()
                    for j in range(n):
                        for i in range(n):
                         # you will have to add a code line for creating a folder here
                            parent_dir ="slice_"+str(i)+"_"+str(j)
                            box = (weight * i, height * j, weight * (i + 1), height * (j + 1))
                            region = img.crop(box)
                            curr_path =os.path.join(cwd+'\\'+parent_dir)
                            outputfilename = os.path.join(cwd, parent_dir,filename)
                            region.save(outputfilename,'bmp')

You could convert your slice series into a 3D image, see DICOM example. Dealing with 3rd dimension then becomes much easier.

If you take this chunked processing example and replace median filter with RegionOfInterest you can do arbitrary processing with the resulting chunk.

2 Likes