I've asked this question already, but I've given it a go since. Here's my
code, with a doc string to show what I'm trying to do.
"""
w1_w2_filter_mask2.py
Use xbulge-mask.fits image file as a mask for W1 and W2 bands
and compute the median in patches where the image is not masked
"""
import matplotlib.pyplot as plt
import numpy as np
from astropy.io import fits
from scipy.ndimage.filters import generic_filter as gf
# Open data files
hdulist = fits.open('xbulge-w1.fits')
w1data = hdulist[0].data
hdulist2 = fits.open('xbulge-w2.fits')
w2data = hdulist2[0].data
hdulistmask = fits.open('xbulge-mask.fits')
maskdata = hdulistmask[0].data
# Define physical shape of filter patch
def patch_filter(image_data, radius):
kernel = np.zeros((2*radius+1, 2*radius+1))
y, x = np.ogrid[-radius:radius+1, -radius:radius+1]
patch = x**2 + y**2 <= radius**2
kernel[patch] = 1
filtered_image = gf(image_data, np.median, footprint = kernel)
return filtered_image
# Apply mask to image files
mx1 = np.ma.masked_array(w1data, mask=maskdata)
mx2 = np.ma.masked_array(w2data, mask=maskdata)
# Pass median filtering patch across masked image
radius = 25
w1masked_filtered = patch_filter(mx1, radius)
w2masked_filtered = patch_filter(mx2, radius)
When I print or imshow the masked, filtered array, it has the same effect as when I don't apply the mask image, i.e. (load mask -> load image -> apply mask -> filter in patches) has the same effect as (load image -> filter in patches).
Can anyone see what I'm missing?
Related
I have an image with 22500x55000x3 shape and I want to apply kmean algorithm on this image. Unfortunatelly it takes so much time even if I run the algorithm in a server. What can be done for this situation ?
Here the code I used.
import os
os.environ["OPENCV_IO_MAX_IMAGE_PIXELS"] = pow(2,40).__str__()
import cv2
import numpy
import json
import matplotlib.pyplot as plt
image = cv2.imread("images/2021/true_color_08.jpg")
mask = cv2.imread("images/2021/09/all_08.jpg")
image = cv2.bitwise_and(image,mask, dst = image)
pixel_values = image.reshape((-1, 3))
# convert to float
pixel_values = numpy.float32(pixel_values)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.2)
k = 4
_, labels, (centers) = cv2.kmeans(pixel_values, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
# convert back to 8 bit values
centers = numpy.uint8(centers)
centers[0] = [255,255,255]
centers[1] = [255,0,0]
centers[2] = [0,255,0]
centers[3] = [0,0,255]
# flatten the labels array
labels = labels.flatten()
segmented_image = centers[labels]
# reshape back to the original image dimension
segmented_image = segmented_image.reshape(image.shape)
# show the image
plt.imshow(segmented_image)
plt.show()
I am trying to implement dimming method to dim a image by converting pixel values and using this equation X(new) = 0.5 * X(old)^2. I did some googling and but could not succeed. Here is my code:
import math
from PIL import Image
import numpy as np
from skimage import color, io
import matplotlib.pyplot as plt
def load(image_path):
out = plt.imread(image_path)
out = out.astype(np.float64) / 255
return out
def dim_image(image):
out = image.point(lambda x: x*0.5)
return out
def display(img):
# Show image
plt.figure(figsize = (5,5))
plt.imshow(img)
plt.axis('off')
plt.show()
image1 = load(image1_path)
image2 = load(image2_path)
display(image1)
display(image2)
new_image = dim_image(image1)
display(new_image)
You are trying to use .point on a numpy array, which doesn't exist. I assume you meant to reduce all color values by 50% to dim the image, in which case you should use np.dot (docs):
def dim_image(image):
out = np.dot(image, 0.5)
return out
I have to filter high frequencies from the input image and I know that Gaussian filter is good in this task. First I transform my image:
import cv2
import numpy as np
from numpy.fft import fft2, ifft2, fftshift, ifftshift
...
image = fftshift(fft2(image))
image_real = image.real
image_imag = image.imag
get the shape of image, blur it and combine
x, y = image.shape
image_real_filter = cv2.GaussianBlur(image_real, (x, y), 0)
image_imag_filter = cv2.GaussianBlur(image_imag, (x, y), 0)
image = image_real_filter + 1j * image_imag_filter
And transform it back.
image = ifft2(ifftshift(image))
It should filter high frequencies but it doesn't I get the black image.
Trying to extract the pixels outside and inside the edges within it's own area, currently i am applying the scipy Sobel filter like this:
im = scipy.misc.imread(filename)
im = im.astype('int32')
dx = ndimage.sobel(im, axis=0)
dy = ndimage.sobel(im, axis=1)
mag = np.hypot(dx, dy)
mag *= 255.0 / np.max(mag)
scipy.misc.imsave('sobel.jpg', mag)
Currently the results are:
The idea is to get the pixels outside the edge detection, for example these areas:
How can i extract an array of the area outside and inside the sobel filter?
Here's an approach using interactive image segmentation. In this approach, you must manually label some of the foreground pixels and some of the background pixels, like this:
(I did the labeling in MS Paint.) The code below uses the function skimage.segmentation.random_walker to do the image segmentation, and produces this segmented image:
(This approach can also handle images with much more complicated background regions.) Here's the code:
import skimage
import skimage.viewer
import skimage.segmentation
import skimage.data
import skimage.io
import matplotlib.pyplot as plt
import numpy as np
img = skimage.io.imread("D:/Users/Pictures/img.jpg")
imgLabeled = skimage.io.imread("D:/Users/Pictures/imgLabeled.jpg")
redChannel = imgLabeled[:,:,0]
greenChannel = imgLabeled[:,:,1]
blueChannel = imgLabeled[:,:,2]
markers = np.zeros(img.shape,dtype=np.uint)
markers[(redChannel < 20) & (greenChannel > 210) & (blueChannel < 20)] = 1
markers[(redChannel < 20) & (greenChannel < 20) & (blueChannel > 210)] = 2
plt.imshow(markers)
labels = skimage.segmentation.random_walker(img, markers, beta=1000, mode='cg')
seg1 = np.copy(img)
seg1[labels==2] = 0
seg2 = np.copy(img)
seg2[labels==1] = 0
# plt.imsave("D:/Users/Pictures/imgSeg.png",seg1)
plt.figure()
plt.imshow(seg1)
plt.figure()
plt.imshow(seg2)
I am working on image processing with python. Specifically, I am trying to implement an algorithm called Structural similarity index measure (SSIM) between two images (x and y), which I extracted from this article this article.
In that formula I need the covariance between the two images. I know how to calculate the covariance between two vectors, but I don't know how to calculate the covariance of two matrices (I assume each image is a matrix of pixels), anyone can help me? I tried using the numpy function numpy.cov(x,y) [doc] but I have a large 3-D matrix, and I actually need a scalar value
Using python we can calculate covariance between two images with following way
import numpy as np
def Covariance(x, y):
xbar, ybar = x.mean(), y.mean()
return np.sum((x - xbar)*(y - ybar))/(len(x) - 1)
now take two images img1,img2 and call the function and print it as given way
print( Covariance(img1,img2))
Check this library: pyssim. Might be what you're looking for.
import cv2
import numpy as np
from PIL import Image, ImageOps #PIL = pillow
from numpy import asarray
'''read image via PIL -- in opencv it equals to img1 = cv2.imread("c1.jpg") '''
img1 = Image.open('c1.jpg')
img2 = Image.open('d1.jpg')
gimg1 = ImageOps.grayscale(img1) #convert to grayscale PIL
gimg2 = ImageOps.grayscale(img2)
#asarray() class is used to convert PIL images into NumPy arrays
numpydata1 = asarray(gimg1)
numpydata2 = asarray(gimg2)
print("Array of image 1: ", numpydata1.shape)
print("Array of image 2: ", numpydata2.shape)
#grayscale images are saved as 2D ndarray of rows(height) x columns(width)
height = int(numpydata2.shape[0] *
(numpydata1.shape[0]/numpydata2.shape[0] ) )
width = int(numpydata2.shape[1] * (numpydata1.shape[1]/
numpydata2.shape[1] ) )
#print(width)
#print(height)
#when using resize(), format should be width x height therefore, create a new image called new and set it to w x h
new = (width, height)
#resize image so dimensions of both images are same
resized = cv2.resize(numpydata2, new, interpolation = cv2.INTER_AREA)
print("Array of resized image 2: ", resized.shape)
def Covariance(x, y):
xbar, ybar = x.mean(), y.mean()
return np.sum((x - xbar)*(y - ybar))/(len(x) - 1)
print( Covariance(numpydata1, resized))
'''#Alternative Method - convert grayscale image to array using np.array
np_img1 = np.array(gimg1)
np_img2 = np.array(gimg2)
'''