A more streamlined method for displaying an image on a 3D plane in matplotlib that doesn't involve using a meshgrid

Looking for an improved method to create a 3D plot of a plane with an image using matplotlib? Here is one way:

xx, yy = np.meshgrid(np.linspace(0, 1, img_size[1]), np.linspace(0, 1, img_size[0]))
zz     = np.ones((img_size[0],img_size[1]))
ax.plot_surface(xx, yy, zz, rstride=1, cstride=1, facecolors=img / 255, shade=False)

I want to avoid generating a surface with the same number of faces as pixels due to inefficiency. Do you have any suggestions for improvement?

Check out how my current plot looks like:

https://i.stack.imgur.com/0P2dX.png

Answer №1

If you're looking to quickly downsample an image, one simple method is to use array slicing like this: img_smaller = img[::10, ::10, :]. Keep in mind that this will decrease the size of the image by a factor of 10 without applying any interpolation, which can result in a coarse appearance and possible clipping of edges if the dimensions are not multiples of 10:

Here's how the image looks before downsampling:

https://i.stack.imgur.com/jYKuv.png

After downsampling using array slicing:

https://i.stack.imgur.com/g1Ec0.png

Alternatively, another approach is to downsample the image after loading it with the help of the PIL library. By setting downsample=12, you achieve a downsampling of 12x:

https://i.stack.imgur.com/5ua1E.png

Using PIL for downsampling:

from PIL import Image

#Load image or create a test image
np.random.seed(0)
img = Image.fromarray(np.random.randint(0, 255, size=(100, 100, 3), dtype=np.ubyte))
img = Image.open('../image.png')

#Downsample 12x and apply interpolation
downsample = 12
img_small = img.resize((img.height // downsample, img.width // downsample),
                       resample=Image.BICUBIC)
h, w = img_small.height, img_small.width
img_small_arr = np.asarray(img_small)

#Plotting
ax = plt.figure(figsize=(3, 3)).add_subplot(projection='3d')
xx, yy = np.meshgrid(np.linspace(0, 1, w), np.linspace(0, 1, h))
zz     = np.ones((h, w))
ax.plot_surface(xx, yy, zz, facecolors=img_small_arr / 255, shade=False)
                #facecolor=[0,0,0,0], linewidth=1) #optionally add a 'grid' effect

A one-liner method using slicing:

#Downsample using slicing
img_small_arr = np.asarray(img)[::10, ::10, :]

#New dimensions
h, w, _ = img_small_arr.shape

#Continue plotting as previously done
ax = plt.figure(figsize=(3, 3)).add_subplot(projection='3d')
xx, yy = np.meshgrid(np.linspace(0, 1, w), np.linspace(0, 1, h))
zz     = np.ones((h, w))
ax.plot_surface(xx, yy, zz, facecolors=img_small_arr / 255, shade=False)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding information to a MySQL database table with Python

As a Python beginner, I am attempting to insert JSON file data into my database table using Python. However, despite not encountering any errors, I only receive the message: Tweet number 49634 is uploading to the server I'm struggling to identify wh ...

What is the best way to insert information into a complicated JSON dictionary using Python?

My task involves populating a JSON API Payload before sending it in the API request. The process includes working with 2 files: A text file containing JSON payload format, named json.txt A yml file containing actual data, named tdata.yml. I am developing ...

Retrieving the current webpage URL without using Selenium

Is there a way to extract an authorization code from an Oauth2 redirect URI without using Selenium Webdriver? When a user clicks "allow" on the Oauth2 consent form, they are redirected back to a specified URL with an important authorization code in the pa ...

Obtaining a series of coordinates from a Numpy array

I have a 100x100x100 numpy array that represents a 3D volume composed of 2D slices. My goal is to conduct cross correlation on the object in this volume across multiple volumes using a template derived from the volume with the best signal-to-noise ratio. ...

Unable to bounce back from a stack overload

While learning Python, I created a small script that seems to run into a stack overflow error when the server disconnects. Here is my script: #/user/bin/python import os import socket import subprocess import errno import threading s = socket.socket() ...

What is the best way to centralize all of the loggers from different modules under a single parent?

While I appreciate and support the hierarchical structure of loggers with canonical module names, I am facing a challenge in bringing everything together at the top level. For example, my application utilizes package1.subpackage1.module1 and package2.sub ...

Image upload to local blob store encountered an Error 404

Recently, I delved into the world of Python app engine development and attempted to run the source code from https://cloud.google.com/appengine/docs/python/blobstore/#Python_Complete_sample_application. However, upon selecting an image file and clicking s ...

There was a problem with the length of an object that has the type of 'NoneType'

x=[] while len(x)<10: x=x.insert(2, 5) The code above is returning an error in the line where the while loop is located. The specifics of this error are highlighted in the title of this question. How should I address this issue? ...

How can I print a set in Python in the order it was initially declared?

Exploring Python for the first time has been a bit confusing with all the "why's" and "how's." Recently, I came across "SETS" in Python and noticed that when I print it out, it doesn't maintain the same order as when I declared it. Here&apos ...

Combine a column in pandas when all rows are identical

Name Class Marks1 Marks2 AA CC 10 AA CC 33 AA CC 21 AA CC 24 I am looking to reformat the data from the original structure shown above to: Name Class Marks1 Marks2 AA CC 10 33 AA CC 21 ...

Error: The 'charmap' codec is having trouble encoding a character which is causing issues

Before anyone criticizes me for asking the same question multiple times, I want to clarify that I have tried various suggestions from different threads, but none of them have effectively solved my issue. import json def parse(fn): results = [] wit ...

Issue: "TypeError: 'module' object is not callable" encountered while attempting to visualize a decision tree for a machine learning model

After writing the code to visualize the decision tree model, I initially faced errors such as 'graphviz's executables not found'. However, I managed to resolve this issue by adding the path to the environment variables and re-installing the ...

Invalid operator detected in TypeT5

File "/work/09235/kunjal/ls6/TypeT5/train_model.py", line 112, in <module> wrapper = train_spot_model( File "/work/09235/kunjal/ls6/TypeT5/typet5/train.py", line 180, in train_spot_model trainer.fit( File "/home1/ ...

Need help automating clicking the download csv button with Selenium Python, but the button's class name changes when it's hovered over?

While attempting to save a csv file by clicking the download csv button on a website, I encountered an issue. It seems that the .click() action is not functioning as expected, and upon inspection, I noticed that the class-name of the button changes from &a ...

Error message displayed by Django-ratings: "The rating value should be a Rating instance, not '100"

I'm having trouble sorting a group of model objects by rating using the Django-ratings app. I've created an order_by function in my view that is functioning correctly, except when it comes to sorting by the rating field. In this case, I am receiv ...

Step-by-step guide on correctly plotting the image after converting it to an array using the img_to_array function

I'm trying to figure out how to plot an image that has been converted into an array using keras.preprocessing.image.img_to_array. Here's my approach. To provide a simple example, I downloaded a picture of a duck from the internet: import urllib ...

How can I store a date from a calendar using tkcalendar in Python?

I'm looking to save the selected dates from a calendar to variables. I found this code, but I'm unsure of how to save the date. import tkinter as tk from tkinter import ttk from tkcalendar import Calendar def example1(): def print_sel(): ...

The Aggrid table vanishes when the user clicks on the column header

When I click the button, the AgGrid table is displayed. However, when I click on the table, it disappears. How can I make it persistent? uploaded_file = st.file_uploader('Upload your text/csv file here') def check_upload(): if upl ...

Performing computations on large dense matrices using numpy

As I embark on training a neural network, I am faced with a significant challenge. I have a massive 212,243 × 2500 dense matrix labeled phi, along with vectors y (212243) and w (2500). These are stored as numpy arrays of double values. My goal is to calcu ...

generate a graph for the top 20 most common words in the

Currently, I am attempting to display the most frequently used words in a plot, however, I am encountering an issue due to the language being Arabic which does not align with the format. fig, ax = plt.subplots(figsize=(12, 10)) sns.barplot(x="word", y="fr ...