Создание копии файла изображения при обработке в python

Я обрабатываю файл BMP и в настоящее время конвертирую его в оттенки серого. Однако я использую rb+, который записывает в тот же файл и сохраняет оригинал как обработанный. Как мне обработать файл изображения, который фактически делает копию оригинала и обрабатывает его, а не уничтожает оригинал?

Вот код

from io import SEEK_CUR

def main():
    filename = input("Please enter the file name: ")

    # Open as a binary file for reading and writing
    imgFile = open(filename, "rb+")

    # Extract the image information.
    fileSize = readInt(imgFile, 2)
    start = readInt(imgFile, 10)
    width = readInt(imgFile, 18)
    height = readInt(imgFile, 22)

    # Scan lines must occupy multiples of four bytes.
    scanlineSize = width * 3
    if scanlineSize % 4 == 0:
        padding = 0
    else :
        padding = 4 - scanlineSize % 4

    # Make sure this is a valid image.
    if fileSize != (start + (scanlineSize + padding) * height):
        exit("Not a 24-bit true color image file.")

    # Move to the first pixel in the image.
    imgFile.seek(start)# Process the individual pixels.
    for row in range(height): #For each scan line
        for col in range(width): #For each pixel in the line
            processPixel(imgFile)

        # Skip the padding at the end.
        imgFile.seek(padding, SEEK_CUR)

    imgFile.close()## Processes an individual pixel.#@param imgFile the binary file containing the BMP image#

def processPixel(imgFile) :
#  Read the pixel as individual bytes.
    theBytes = imgFile.read(3)
    blue = theBytes[0]
    green = theBytes[1]
    red = theBytes[2] #Read the pixel as individual bytes.
    # Process the pixel
    newBlue = 255 - blue
    newGreen = 255 - green
    newRed = 255 - red
    # Process the pixel.



    # Write the pixel.
    imgFile.seek(-3, SEEK_CUR)# Go back 3 bytes to the start of the pixel.

    imgFile.write(bytes([newBlue, newGreen, newRed]))## Gets an integer from a binary file.#@param imgFile the file#@ param offset the offset at which to read the integer#@
##  Gets an integer from a binary file.
# @param imgFile  the file
# @param offset  the offset at which to read the integer
# @return  the integer starting at the given offset
#

def readInt(imgFile, offset): #Move the file pointer to the given byte within the file.
    imgFile.seek(offset)

    # Read the 4 individual bytes and build an integer.
    theBytes = imgFile.read(4)
    result = 0
    base = 1
    for i in range(4):
        result = result + theBytes[i] * base
        base = base * 256

    return result# Start the program.
main()

person jacob schiffer    schedule 28.10.2015    source источник
comment
покажи свой код пожалуйста   -  person Julien    schedule 28.10.2015
comment
Это школьное задание, и мне посоветовали никуда не публиковать из-за плагиата. Мой код работает, я просто хочу сделать копию изображения.   -  person jacob schiffer    schedule 28.10.2015
comment
вы не можете показать только несколько проблемных строк: как вы открываете и сохраняете свой файл?   -  person Julien    schedule 28.10.2015
comment
Хорошо, я добавил код   -  person jacob schiffer    schedule 28.10.2015
comment
просто откройте новый файл и скопируйте в него вместо того, чтобы переписывать существующий файл! Используйте, например, scipy.misc.imsave, если вы работаете с изображениями...   -  person Julien    schedule 28.10.2015


Ответы (1)


Я бы рекомендовал сначала сделать копию файла, а затем писать в эту копию.

Вы можете использовать функцию copyfile из модуля shutil для копирования файла. Вот демонстрация того, как скопировать файл:

import shutil  
shutil.copyfile('/path/to/src/file', '/path/to/dest/file')  
person Colin Schoen    schedule 28.10.2015
comment
Звучит неплохо. Пожалуйста, проголосуйте за ответ / отметьте его как решение, если это поможет. - person Colin Schoen; 28.10.2015
comment
О, есть ли способ, при котором мне не нужно писать файл присяги, и он создает копию изображения в том же каталоге. Я отправляю его своему профессору, и у него не будет того же каталога, что и у меня. - person jacob schiffer; 28.10.2015
comment
Просто укажите имя файла, если он находится в текущем рабочем каталоге. Пример: импорт Shutil Shutil.copyfile('file.extension', 'new_file.extension') - person Colin Schoen; 28.10.2015
comment
Хорошо, я не мог заставить его работать. Я разместил свой код сейчас. Можете ли вы реализовать это в этом? Спасибо. - person jacob schiffer; 28.10.2015