You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. Reads an image and converts it to a double type (pixel values stay 0-255, just stored as floats)
  2. Reshapes the image into a 1200×1 vector
  3. Scales every pixel value by dividing by 256 (turning 0-255 into ~0 to ~0.996)
  4. Rounds those scaled values to get either 0 or 1
  5. 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 /256 and rounding steps that turn those numbers into 0s and 1s.
  • im2double isn'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.png in Python but play.png in 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's double() function.
  • message.flatten()[:1200]: Flattens the 2D image into a 1D array, then takes the first 1200 elements to match MATLAB's reshape(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's round(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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:33:27