Matlab转Python:如何将二值图像转为含0和1的1D vector?
Fixing Your Python Code to Match MATLAB's 0/1 Vector Output
Hey there! Let's break down what's off with your current Python code and adjust it to get the exact 0/1 1D vector your MATLAB code produces.
What Your MATLAB Code Actually Does
First, let's recap the key steps in your MATLAB script to make sure we replicate them:
- Reads an image and converts it to a
doubletype (pixel values stay 0-255, just stored as floats) - Reshapes the image into a 1200×1 vector
- Scales every pixel value by dividing by 256 (turning 0-255 into ~0 to ~0.996)
- Rounds those scaled values to get either 0 or 1
- Prints the final vector
Issues in Your Python Code
- Missing scaling and rounding: Your code just reshapes the raw 0-255 grayscale values, skipping the critical
/256and rounding steps that turn those numbers into 0s and 1s. im2doubleisn't a Python function: This is a MATLAB-specific function—Python doesn't have it built-in, so that line would throw an error unless you've defined it elsewhere.- Reshape mismatch: MATLAB explicitly reshapes to 1200×1, but your code reshapes to a vector of the image's full pixel count. Unless your image is exactly 1200 pixels total, this will give a different length vector.
- Image file mismatch: You're reading
sam.pngin Python butplay.pngin MATLAB—make sure you're using the same image file!
Corrected Python Code
Here's the adjusted code that mirrors your MATLAB logic perfectly:
import cv2 import numpy as np # Read the same image as your MATLAB code water = cv2.imread('play.png') # Convert to grayscale (matches MATLAB's implicit grayscale read if the image is RGB) gray_image = cv2.cvtColor(water, cv2.COLOR_BGR2GRAY) # Convert to float64 (equivalent to MATLAB's double() conversion) message = gray_image.astype(np.float64) # Reshape to 1200×1 vector, scale by 256, then round to get 0/1 message_vector = np.round(message.flatten()[:1200].reshape(1200, 1) / 256) # Print the result print(message_vector)
Key Explanations
astype(np.float64): Converts the 8-bit grayscale image (0-255 uint8) to floating-point values, just like MATLAB'sdouble()function.message.flatten()[:1200]: Flattens the 2D image into a 1D array, then takes the first 1200 elements to match MATLAB'sreshape(message,1200,1)(if your image has fewer than 1200 pixels, you might need to adjust this, but it aligns with your original MATLAB code).np.round(...) / 256: Exactly replicates MATLAB'sround(reshape(...)./256)—scaling the pixel values down to a range near 0, then rounding to get binary 0/1 values.
Run this code, and you'll get the same 0/1 vector as your MATLAB script!
内容的提问来源于stack exchange,提问作者Hero31
相关产品推荐
相关产品推荐

