Resizing ROI in an image - image

I have a 565 * 584 image as shown
I want to reduce the radius of the circle by certain number of pixels without changing the size of the image. How can I do it? Please explain or give some ideas. Thank You.

I would use ImageMagick and an erosion like this:
convert http://i.stack.imgur.com/c8lfe.jpg -morphology erode octagon:8 out.png

If you know that the background of the image is a constant, as in your example, this is easy.
Resize the entire image by the ratio you wish to shrink by. Then create a new image at the size of the original and fill it with the background color, then paste the resized image into the center of it.

Here's how you'd do it in OpenCV Python. Going with Mark Setchell's approach, simply specify a round structuring element so that you can maintain or respect the round edges of the object. The closest thing that OpenCV has to offer is the elliptical mask.
As such:
import numpy as np # Import relevant packages - numpy and OpenCV
import cv2
# Read in image and threshold - convert to grayscale first
im = cv2.imread('c8lfe.jpg', 0) > 128
# Specify radius of ellipse
radius = 21
# Obtain structuring element, then erode image
se = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (radius, radius))
# Make sure you convert back to grayscale and multiply by 255
out = 255*(cv2.erode(im, se).astype('uint8'))
# Show the image, wait for user key, then close window and write image
cv2.imshow('Reduced shape', out)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite('out.png', out)
We get:
Be advised that the small bump at the top right corner of your shape will mutate. As we are essentially shrinking the perimeter of the object, that bump will also shrink as well. If you wish to preserve the structure of the object while maintaining the image resolution, use Mark Ransom's approach or my slightly modified version of his approach. Both are shown below.
However, to be self-contained, we can certainly do what Mark Ransom has suggested. Resize the image, initialize a blank image that is size of the original image, and place it in the centre:
import numpy as np # Import relevant packages - OpenCV and Python
import cv2
im = cv2.imread('c8lfe.jpg', 0) # Read in the image - grayscale
scale_factor = 0.75 # Set scale factor - We are shrinking the image by 25%
# Get the desired size (row and columns) of the shrunken image
desired_size = np.floor(scale_factor*np.array(im.shape)).astype('int')
# Make sure desired size is ODD for easier placement
if desired_size[0] % 2 == 0:
desired_size[0] += 1
if desired_size[1] % 2 == 0:
desired_size[1] += 1
# Resize the image. Columns come first, followed by rows, which is why we
# reverse the desired_size array
rsz = cv2.resize(im, tuple(desired_size[::-1]))
# Determine half width of both dimensions of shrunken image
half_way = np.floor(desired_size/2.0).astype('int')
# Create output image that is the same size as the input and find its centre
out = np.zeros_like(im, dtype='uint8')
centre = np.floor(np.array(im.shape)/2.0).astype('int')
# Place shrunken image in the centre of the larger output image
out[centre[0]-half_way[0]:centre[0]+half_way[0]+1, centre[1]-half_way[1]:centre[1]+half_way[1]+1] = rsz
# Show the image, wait for user key, then close window and write image
cv2.imshow('Reduced shape', out)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite('out.png', out)
We get:
Another suggestion
What I can also recommend you do is pad the array with zeroes, then reshrink the image back to its original size. You would essentially extend the borders of the original image so that the borders contain zeroes. In this case, we would do what Mark Ransom also suggested, but we are working within the inside, out.
Here's the way to pad a matrix with zeroes using OpenCV C++: Pad array with zeros- openCV . However, in Python, simply use numpy's pad function:
import numpy as np # Import relevant packages - numpy and OpenCV
import cv2
# Read in image and threshold - convert to grayscale first
im = cv2.imread('c8lfe.jpg', 0)
# Set how many pixels along the border you want to add on each side
pad_radius = 75
# Pad the image
out = np.lib.pad(im, ((pad_radius, pad_radius), (pad_radius, pad_radius)), 'constant', constant_values=((0,0),(0,0)))
# Shrink it back to what the original size was
out = cv2.resize(out, im.shape[::-1])
# Show the image, wait for user key, then close window and write image
cv2.imshow('Reduced shape', out)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite('out.png', out)
We thus get:

Related

How to create a 1 pixel white .gif from code only

I'm new to programming, i won't become a developer but I like to learn a few stuff, since i'm a creative artist. I'm trying to solve an exercise I came up with.
I'm looking for guidelines to create a 1 pixel image from code. I want to try to create the most basic form of a white image, and I thought that a lossless 1 pixel gif of white (#FFFFFF or RGB 255, 255, 255) could be the simplest form, generating the smallest code possible.
Where would I even start?
I created two 1 pixel white .gifs, one in Paint and another in Photoshop, using 8bit Grayscale color mode. Gave both of them the same name, and when I hash them, both hashes are different, so they are not exactly the same. I also tried exporting from photoshop twice, to different directories, and this time hashes are the same.
My intention is to create the simplest and purest form of that white pixel.
Tips?
In Python, you can use PIL to create an image. Here is the code for what you requested.
from PIL import Image # import library
img = Image.new(mode = "RGB", size = (1,1)) # creates a RGB image with the size of 1x1
pixels = img.load() # Creates the pixel map
pixels[0,0] = (255,255,255) # Set the colour of the first (and only) pixel to white
img.save(format='GIF', fp='./test.gif')
# Saves the image as a GIF in a file called test.gif in your current directory
The purest, simplest form that is widely readable (GIMP, Photoshop, MS-Paint) is NetPBM IMHO.
Here is a single white pixel - no metadata, no copyright, no EXIF, no creation date, no palette, no checksum. You can create it with a text editor or code:
P1
1 1
0
Save it as white.pbm
If you want a simple, single, red pixel, save the following as red.ppm:
P3
1 1
255
255 0 0
The simplest Python to create a white single pixel GIF with PIL is probably:
from PIL import Image
Image.new('L', (1,1), 255).save('white.gif')
The simplest Python to create a red single pixel GIF with PIL is probably:
from PIL import Image
Image.new('RGB', (1,1), 'red').save('red.gif')

How to draw single pixels in python Pillow from Numpy arrays without producing pixel noise?

I am stuck with a basic problem to which I was not able to find any answer nor solution no matter what I tried. Please help me out and enlighten me, what I am doing wrong :-)
Task:
Make a Numpy array of Pixels, manipulate them by an algorithm and then print an image from that array.
Occuring Problem:
When I manipulate single pixels this way, there is noise artifacts appearing next to manipulated pixels (see example pictures)
Details - What I want to do:
I have a numpy array to create an image from.
The array is created as black:
shape = np.zeros((100, 100, 3), dtype=np.uint8)
Now I want to manipulate single pixels by an algorithm, for instance:
color = (255, 255, 255)
shape[50, 50] = color
There will be 100s and 1000s of pixels manipulated in color this way.
At the end, I want to make an image from that shape array and print it to the screen:
arr_image = Image.fromarray(shape, 'RGB')
arr_image.save('test.jpg')
Details - What I tried:
No matter, what I do, I get pixel noise next to created pixels in images created using the example code!
I tried:
Searching the Internet/Stackoverflow: No such problem described/found
Taking working code from other examples and manipulate to my needs: Same artifacts occuring after manipulation
Drawing pixels in the created image after making a black-only (0,0,0) image from a numpy array by using Image method putpixel: Same artifacts appearing
Changing up syntax: Same artifacts appearing
Checking the underlying numpy arrays for grey values at the position of the artifacts: THERE IS NO SUCH GREY VALUES IN THE ARRAYS!!
When using Pillow method show(), the pixel noise is gone (!) in the windows popup, however (!!!), when I open the image from outside python, the pixel noise is in the exact same image visible (!!!!!!!!!!!!!)
Example code that produces this problem:
import numpy as np
from PIL import Image
shape = np.zeros((100, 100, 3), dtype=np.uint8)
white = (255, 255, 255)
shape[50][50] = white
arr_image = Image.fromarray(shape, 'RGB')
# arr_image.putpixel((50, 50), white)
arr_image.save('test.jpg')
Example images:
Black Array
[Same Array, but point 50][50] is set to white
[Same Array, but 100 random points were placed at x][y] and set to white
The solution to this is: Do not use .jpg data, the compression of this format causes observed pattern.
When using .png, the bug was instantly solved! In this image (.png), you can now see that there is 0 pixel noise nor strange artifact patterns, when generating an array-based image as described above: enter image description here
Thank you #dantechguy and #Mark Setchell, you guys saved me! :-))

Using PIL (Pillow) and Image but keeping a good resolution

I'm using PIL to resize my images. Most of them are 640x480, some of them are bigger. Most of them are in png, but I have jpeg extension too.
I want to resize all my images to be 32x32 pixels, but I noticed that the resolution seems to change after using PIL.
I found that is a typical question and It's often a problem that figure out when you are saving the image.
I tried with different values of "quality", I read the documentation trying different parametres such as "subsampling" and trying both jpeg and png format.
Here is my code:
from PIL import Image
im = Image.open(os.path.join(my_path, file_name))
img = im.resize((32, 32))
if grey_scale is True:
img = img.convert('L') # to resize image in gray scale
img.save(os.path.join(my_path,
file_name[:file_name.index('.')] + '.jpg'), "JPEG", quality=100)
Here I have my input image
Here I have the grainy output obtained with my code
How can I resize my images to be smaller, but keeping a very good resolution?
The sort of image transformation you want is not possible. As when you try to resize an raster image to a lower pixel dimensions, you have to either Downsample it, or not sample it at all(simple resize). Even though you may preserve the resolution (total no of pixels in an image) but still since a pixel can represent one color at a time (atleast in a sub-pixel based display like a monitor), and your final image only has 1024 of them, and the detail in the original image is far more then what could be represented by these number of pixels, this would always result in a considerably lower quality(pixelated image with artifacts) in the final image.
But this is not the general case, as it depends a lot on what sort of details are represented by the image. If the image is not complex (not contains a lot of color changes), then it can be resized to a considerably lower quality version of it without losing details.
746x338 dimension image
32x32 dimension version of previous image
There is almost no difference between both the images (except for their physical size), even though their dimension's are a lot different. The Reason being these are non-complex images containing same pixel value over a large range, which makes it easier to resize them without loss in detail.
Now if the same process is tried out on a complex image, like the one you gave in the question, the result would be an Pixelated image.
SOLUTION:-
You can either choose for a large dimension value in the final image
(a lot more then 32x32) if you want to preserve the image quality.
Create a Vector equivalent of your image, which is resolution
independent and can be resized to a larger/smaller physical size
without affecting image quality.
P.S.:-
Don't save a .png image with .jpgextension, as jpg is a lossy compression technique(for the most part), which in turn results in a lower quality final image, then the original even if no manipulation are made over it.
Reducing the size, you can't keep the image crisp, because you need pixels for those and you can't keep both
There are different filters you can use in this case. See the below code
from PIL import Image
import os
import PIL
filters = [PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.BICUBIC, PIL.Image.ANTIALIAS]
grey_scale = False
i = 0
for filter in filters:
im = Image.open("./image.png")
img = im.resize((32, 32), filter)
if grey_scale is True:
img = img.convert('L') # to resize image in gray scale
i = i + 1
img.save("./" + str(i) + '.jpg', "JPEG", quality=100)
Results:
Next, using resize you don't maintain the aspect ratio. So instead of using resize, use the thumbnail method which keeps aspect ratio as well
from PIL import Image
import os
import PIL
filters = [PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.BICUBIC, PIL.Image.ANTIALIAS]
grey_scale = False
i = 5
for filter in filters:
im = Image.open("./image.png")
img = im.thumbnail((32, 32), filter)
img = im
if grey_scale is True:
img = img.convert('L') # to resize image in gray scale
i = i + 1
img.save("./" + str(i) + '.jpg', "JPEG", quality=100)
Results:

Lung segmentation in Matlab

Trying to segment out the lung region, I am having a lot of trouble. Incoming image is like this: (This is essentially a jpg conversion, and each pixel is 8 bits.)
I = dicomread('000019.dcm');
I8 = uint8(I / 256);
B = im2bw(I8, 0.007);
segmented = imclearborder(B);
Above script generates:
Q-1
I am interested in entire inner black part with white matter as well. I have started matlab couple of days ago, so not quite getting how can I do it. If it is not clear to you what kind of output I want, let me know-I will upload an image. But I think there is no need.
Q-2
in B = im2bw(I8, 0.007); why I need to give a threshold so low? with higher thresholds everything is white or black. I have read the documentation and as I understand it, the pixels with value less than 0.007 are marked black and everything above is white. Is it because of my 16-to-8 bit conversion?
An other automatic solution that I did quickly using ImageJ (there are the same algorithms in MatLab):
Automatic thresholding using Huang or Li in the color space of your choice (all of them work)
Opening with a structuring element of type disk (delete the small components)
Connected components labeling.
Delete the components that touches the border of the images.
Fill holes.
And you have a clean result.
Here's a working solution in python using OpenCV:
import cv2 #openCV
import numpy as np
filename = 'zFrkx.jpg' #name of file in quotations here... assumes file is in same dir as .py file
img_gray = cv2.imread(filename, 0) #converts jpg image to grayscale representation
min_val = 100 #try shifting these around to expand or collapse area of interest
max_val = 150
ret, lung_mask = cv2.threshold(img_gray, min_val, max_val, cv2.THRESH_BINARY_INV) #fixed threshold uses values you'll def above
lung_layer = cv2.bitwise_and(img_gray, img_gray, mask = lung_mask)
cv2.imwrite('cake.tif', lung_layer) #outputs desired layer to current working dir
I tried running the script with threshold values set arbitrarily to 100,150 and got the following result, from which you could select the largest continuous element using dilation and segmentation techniques (http://docs.opencv.org/master/d3/db4/tutorial_py_watershed.html#gsc.tab=0).
Also, I suggest you crop the bottom and top X pixels to cut out text since no lung will fill the top or bottom of the picture.
Use tif instead of jpg format to avoid compression related artifact.
I know you noted that you'd like the medullar(?) white matter, too. Would be glad to help with that, but could you first explain in plain english how your shared matlab code works? Seems to work pretty well for the WM.
Hope this helps!

Converting to 8-bit image causes white spots where black was. Why is this?

Img is a dtype=float64 numpy data type. When I run this code:
Img2 = np.array(Img, np.uint8)
the background of my images turns white. How can I avoid this and still get an 8-bit image?
Edit:
Sure, I can give more info. The single image is compiled from a stack of 400 images. They are each coming from an .avi video file, and each image is converted into a NumPy array like this:
gray_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
A more complicated operation is performed on this whole stack, but does not involve creating new images. It's simply performing calculations on each 1D array to yield a single pixel.
The interpolation is most likely linear (the default in plotting images with matplotlib. The images were saved as .PNGs.
You probably see overflow. If you cast 257 to np.uint8, you will get 1. According to a google search, avi files contain images with a color depth of 15 - 24 bit. When you cast this depth to np.uint8, you will see white regions getting darkened and (if a normalization takes place somewhere) also dark regions getting white (-5 -> 251). For the regions that become bright, you could check whether you have negative pixel values in the original image Img.
The Docs say that sometimes you have to do some scaling to get a proper cast, and to rather use higher depth whenever possible to avoid artefacts.
The solution seems to be either working at higher depth, i.e. casting to np.uint16 or np.uint32, or to scale the pixel values before reducing the depth, i.e. with Img2 already being a numpy matrix
# make sure that values are between 0 and 255, i.e. within 8bit range
Img2 *= 255/Img2.max()
# cast to 8bit
Img2 = np.array(Img, np.uint8)

Resources