Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have an image of shape (31278,25794,3). I would like to know how is possible to obtain MxN segment of the picture, using np functions. For example starting from:
I would like to obtain:
In numpy you can split a picture like you slice an array.
Here's an example with your image:
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
img = np.array(Image.open("cat.jpg"))
plt.imshow(img)
xs = img.shape[0]//2 # division lines for the picture
ys = img.shape[1]//2
# now slice up the image (in a shape that works well with subplots)
splits = [[img[0:xs, 0:ys], img[0:xs, ys:]], [img[xs:, 0:ys], img[xs:, ys:]]]
fig, axs = plt.subplots(2, 2)
for i in range(2):
for j in range(2):
axs[i][j].imshow(splits[i][j])
Keep in mind that the splits here are views into the original array, not arrays with new data, so changes you make to the views will change the original data. If you don't want this, you can do something to copy the data after slice up the array.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
Improve this question
enter image description here
import numpy as np
import numpy.linalg as LA
import pandas as pd
import matplotlib.pyplot as plt
path = "./A.csv";
A = pd.read_csv(path).values;
tposeA = np.transpose(A);
normA = LA.norm(A);
X0 = tposeA / ((normA)**2)
print(X0)
I have been working on this piece and it returns strange result in the matrix, do anyone know what this means?
Many thanks!!
[First col and 4th row]
[0.0089 0.0035 0.0017 0.0053]
[0.0035 0.0089 0.0035 0.0089]
[0.0035 0.0178 0.0106 0.0124]
[0.(blank) 0.0017 0.0124 0.0267]
Since you are looking at floating point numbers, 0. means that the number equals exactly zero. It is the way NumPy displays float.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
This post was edited and submitted for review last year and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I want to split images like this in a way that every symbols gets splits up vertically kind of like this input image:
![input image][1]
to this:
![here][2]
The problem is each symbol might have different width so I can't really fix the splitting points like we do in array splitting. If all objects had same width then I could segment the image base on width. In this scenario, what logic I should use to extract these connected objects?
First load the img from the url
import numpy as np
import urllib.request
from PIL import Image
from matplotlib import pyplot as plt
urllib.request.urlretrieve(
'https://i.stack.imgur.com/GRHzg.png',
"img.png")
img = Image.open("img.png")
img.show()
Then consider the black part as "filled" and convert in numpy array
arr = (np.array(img)[:,:,:-1].sum(axis=-1)==0)
If we sum the rows values for each column we can have a simple sum of how much pixel are filled in each column:
plt.subplot(211)
plt.imshow(arr, aspect="auto")
plt.subplot(212)
plt.plot(arr.sum(axis=0))
plt.xlim(0,arr.shape[1])
finally if we compute the differential of this sum over the columns we can obtain the following result:
plt.subplot(211)
plt.imshow(arr, aspect="auto")
plt.subplot(212)
plt.plot(np.diff(arr.sum(axis=0)))
plt.xlim(0,arr.shape[1])
At this point you can simply chose a threshold and cut the image:
threshold = 25
cut = np.abs(np.diff(arr.sum(axis=0)))>threshold
x_lines = np.arange(len(cut))[cut]
plt.imshow(arr, aspect="auto")
plt.vlines(x_lines, 0, arr.shape[0], color="r")
This is my solution and it works fine, but it is sensitive to the chosen threshold and to the columns gradient. I hope it is useful.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
This is classified image of satellite. Can anybody tell me how to remove these single pixels of filter out them. Remember this is in Geotiff format. I already applied erosion or dilation techniques but no success.
I saw a similar question on SO but can't find it. There were a quite good answer that I remade for myself. So here is the method called particle_filter that will be the solution for your problem:
def particle_filter(image_, power):
nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(image_, connectivity=8)
sizes = stats[1:, -1]
nb_components = nb_components - 1
min_size = power
img2 = np.zeros(output.shape, dtype=np.uint8)
for i in range(0, nb_components):
if sizes[i] >= min_size:
img_to_compare = threshold_gray_const(output, (i + 1, i + 1))
img2 = binary_or(img2, img_to_compare)
img2 = img2.astype(np.uint8)
return img2
def threshold_gray_const(image_, rang: tuple):
return cv2.inRange(image_, rang[0], rang[1])
def binary_or(image_1, image_2):
return cv2.bitwise_or(image_1, image_2)
All you need to do is to call this function and give your binary image as first parameter and filter power as the second.
A bit explanation: Whole method - is simply iterating over objects on an image, and if the area of one of an object is less than the power, then it is simply removed.
I would give a try Median Filter (cv2.medianBlur) which should remove single pixels, but might also have other effect. You need to test it with few different settings and decide if it does provide you acceptable result.
Kernel size should be odd for Median Filter, thus median is used on odd number of pixels (9 for size 3, 25 for size 5, 49 for size 7 and so on), therefore Median Filter never introduces new value, thus if you use binary image as input, you will get binary image as output.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a binary file from which I have to read data. The file consists of a 128x128x243 matrix (hex-formatted) which I have read with the following code:
with open("zubal_voxel_man.dat", "rb") as fileHandle:
dim_x = 128
dim_y = 128
dim_z = 243
data = np.zeros((dim_x,dim_y,dim_z), dtype=np.int)
for p in range(0, dim_x):
for q in range (0, dim_y):
for r in range(0, dim_z):
data[p][q][r] = ord(fileHandle.read(1))
How do I visualize these data with Python? Each x,y,z position has a value from 0 to 255 (grey scale) which I would like to render.
Any help is greatly appreciated!
Part of your problem is with the code:
datax = data[:,0]
datay = data[:,1]
dataz = data[:,2]
Which is not doing what you are expecting of slicing in a single axis it is taking a slice of the Y=0 then of Y=1, Y=2 and plotting them against each other - your other issue is that you have a 3 dimensional array of values which gives each value 4 dimensions X, Y, Z, Value - and you are trying to plot these into a surface. which only has 3 dimensions.
I think that your first priority is to clarify your what your data represents and how it is structured.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to matplotlib, and I want to create a plot, with the following information:
A line joining the medians of around 200 variable length vectors (input)
A line joining the corresponding quantiles of these vectors.
A line joining the corresponding spread (largest and smallest points).
So basically, its somewhat like a continuous box plot.
Thanks!
Using just scipy and matplotlib (you tagged only those libraries in your question) is a little bit verbose, but here's how you would do it (I'm doing it only for the quantiles):
import numpy as np
from scipy.stats import mstats
import matplotlib.pyplot as plt
# Create 10 columns with 100 rows of random data
rd = np.random.randn(100, 10)
# Calculate the quantiles column wise
quantiles = mstats.mquantiles(rd, axis=0)
# Plot it
labels = ['25%', '50%', '75%']
for i, q in enumerate(quantiles):
plt.plot(q, label=labels[i])
plt.legend()
Which gives you:
Now, I would try to convince you to try the Pandas library :)
import numpy as np
import pandas as pd
# Create random data
rd = pd.DataFrame(np.random.randn(100, 10))
# Calculate all the desired values
df = pd.DataFrame({'mean': rd.mean(), 'median': rd.median(),
'25%': rd.quantile(0.25), '50%': rd.quantile(0.5),
'75%': rd.quantile(0.75)})
# And plot it
df.plot()
You'll get:
Or you can get all the stats in just one line:
rd.describe().T.drop('count', axis=1).plot()
Note: I dropped the count since it's not a part of the "5 number summary".