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

课程作业:Python无库实现RGB图像转灰度图遇转换难题

Fixing Your Grayscale Image Conversion with the graphics Library

Hey there! Let's get that grayscale conversion working using only the graphics library you're already using—no extra third-party tools required. Here's how to fill in the missing core logic and get your program fully functional:

Complete Working Code

from graphics import *

def main():
    print("This program will take a colored image \nand make a new image in greyscale")
    filename = input("What is the name of your image: ")
    savefile = input("What would you like the file saved as: ")

    # Load the original color image from file
    original_img = Image(Point(0, 0), filename)
    width = original_img.getWidth()
    height = original_img.getHeight()

    # Create an empty image to hold our grayscale output (matches original dimensions)
    gray_img = Image(Point(0, 0), width, height)

    # Core Grayscale Conversion Logic
    for y in range(height):
        for x in range(width):
            # Extract RGB values from the current pixel
            r, g, b = original_img.getPixel(x, y)
            
            # Calculate weighted grayscale value (matches human visual perception)
            # Weights follow the ITU-R BT.601 standard (more weight to green, since eyes are more sensitive to it)
            gray_value = int(0.2989 * r + 0.5870 * g + 0.1140 * b)
            
            # Create a grayscale color (all RGB channels equal to the calculated gray value)
            gray_color = Color(gray_value, gray_value, gray_value)
            
            # Apply the grayscale color to the corresponding pixel in our new image
            gray_img.setPixel(x, y, gray_color)

    # Save the finished grayscale image
    gray_img.save(savefile)
    print(f"Success! Grayscale image saved as {savefile}")

    # Optional: Display both original and grayscale images side-by-side
    win = GraphWin("Color → Grayscale", width * 2, height)
    # Position and draw original image
    original_img.move(width // 2, height // 2)
    original_img.draw(win)
    # Position and draw grayscale image
    gray_img.move(width + width // 2, height // 2)
    gray_img.draw(win)
    
    # Wait for user to click before closing the window
    win.getMouse()
    win.close()

if __name__ == "__main__":
    main()

Key Explanations

  • Loading & Prepping Images: We first load your input image and create a blank image of the same size to store the grayscale result—this ensures we don't modify the original image.
  • Pixel-by-Pixel Processing: We loop through every pixel in the image (using nested for loops for height and width coordinates). For each pixel:
    1. We grab its red, green, and blue values with getPixel().
    2. We calculate a weighted grayscale value instead of a simple average—this is important because human eyes are more sensitive to green light, so giving it more weight results in a more natural-looking grayscale.
    3. We create a grayscale color by setting all RGB channels to the same calculated value, then apply it to the new image with setPixel().
  • Saving & Display: Finally, we save the grayscale image to your desired filename, and optionally display both images side-by-side so you can see the result immediately.

This code sticks strictly to your requirement of no third-party libraries—all methods used (Image, Color, GraphWin, etc.) are part of the standard graphics library you're already importing.

内容的提问来源于stack exchange,提问作者Gulba

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:46:52