【问题标题】:Pixel Position Value Conversion Output Incorrect像素位置值转换输出不正确
【发布时间】:2021-12-04 15:11:21
【问题描述】:

我整天都在做这个编程挑战,我已经完成了一个 python 程序,对我来说,它应该在逻辑上工作并输出正确的答案——但它没有。我有一个朋友的程序输出正确答案,所以我有办法将我的输出与他们的输出进行比较,但我看不出为什么我的输出也不应该输出正确答案。

挑战是从图像中的像素获取密码,第一行编号为 0..99,第二行编号为 100..199,依此类推。白色像素代表 ascii 代码。特定白色像素的 ascii 代码等于与最后一个白色像素的偏移量。例如,位置 65 处图像的第一个白色像素将表示 ascii 代码 65 ('A'),位置 131 处的下一个白色像素将表示 ascii 代码 (131 - 65) = 66 ('B'),依此类推。

The image used in both programs for the challenge

这是我的代码(输出不正确,Python 3):

import cv2
import numpy as np

# load img
im = cv2.imread('PNG.png')

# define colour
white = [255,255,255]

# get coords
Y,X = np.where(np.all(im==white,axis=2))

a = X.tolist()

# format list to string
x = str(a)

# clean string
x = x.replace(' ', '',)
x = x.replace('[', '')
x = x.replace(']', '')

# reformat CSV string to list
x = x.split(",")

# map each str to int
x = map(int, x)

# convert mapped outputs to list of ints
x = list(x)

firstX = x[0]

print()
print()
print('og list: ',x)
print()
print()

y = list(x)
y.pop(0)
y.insert(len(y),00)
print('conv list: ',y)
print()
print()

length = len(x)

repeatTime = 0

z = []

while repeatTime < 40:
  outputInt = (y[0] - x[0])
  z.insert(len(z),outputInt)
  y.pop(0)
  x.pop(0)
  repeatTime += 1

z.insert(0,firstX)

print(z)
  
# Remove Negative Elements in List
# Using list comprehension
r = [ele for ele in z if ele > 0]


print()
print()
# printing result 
print("List after filtering : " + str(r))


print()
print()
print(r)
print()
print()
v = (''.join(chr(i) for i in r))
print(v)

CODE = {'A': '.-',     'B': '-...',   'C': '-.-.', 
        'D': '-..',    'E': '.',      'F': '..-.',
        'G': '--.',    'H': '....',   'I': '..',
        'J': '.---',   'K': '-.-',    'L': '.-..',
        'M': '--',     'N': '-.',     'O': '---',
        'P': '.--.',   'Q': '--.-',   'R': '.-.',
        'S': '...',    'T': '-',      'U': '..-',
        'V': '...-',   'W': '.--',    'X': '-..-',
        'Y': '-.--',   'Z': '--..',

        '0': '-----',  '1': '.----',  '2': '..---',
        '3': '...--',  '4': '....-',  '5': '.....',
        '6': '-....',  '7': '--...',  '8': '---..',
        '9': '----.' 
        }

CODE_REVERSED = {value:key for key,value in CODE.items()}
 
def from_morse(s):
  return ''.join(CODE_REVERSED.get(i) for i in s.split())

print(from_morse(v))

我的输出:

----.. - -..-- .....--.
-invalid morse code-

这是我朋友的代码(正确的输出,Python 2.7)

from PIL import Image
 
img_file = Image.open("PNG.png")
img_width, img_height = img_file.size
img_pixel = img_file.load()
preposition=0
morse_code=""
answer=""
 
char_morse_dict={
'A':'.-','B':'-...','C':'-.-.','D':'-..','E':'.','F':'..-.',
'G':'--.','H':'....','I':'..','J':'.---','K':'-.-','L':'.-..',
'M':'--','N':'-.','O':'---','P':'.--.','Q':'--.-','R':'.-.',
'S':'...','T':'-','U':'..-','V':'...-','W':'.--','X':'-..-',
'Y':'-.--','Z':'--..','0':'-----','1':'.----','2':'..---','3':'...--',
'4':'....-','5':'.....','6':'-....','7':'--...','8':'---..','9':'----.',
'.':'.-.-.-',',':'--..--','?':'..--..',"'":'.----.','/':'-..-.','(':'-.--.-',
')':'-.--.-',':':'---...',';':'-.-.-.','=':'-...-','+':'.-.-.','-':'-....-',
'_':'..--.-','"':'.-..-.','$':'...-..-','':''
}
 
# fetch ASCII code from image
for y_point in range(img_height) :
    for x_point in range(img_width) :
        if img_pixel[x_point, y_point] == 1 :
            # convert ASCII code to "dits" and "dahs" in morse code
            symbol = chr(x_point + 100 * y_point - preposition)
 
            if symbol != ' ' :
                morse_code += symbol
            else :
                # decode morse code to character
                char = [key for key, value in char_morse_dict.items() if value == morse_code][0]
                answer += char
                morse_code = ""
 
            preposition=x_point + 100 * y_point
# bye bye
print(answer)

他的输出:

--.- --... .-. --... --- ..... .-. --... ..- ..-
Q7R7O5R7UU

我已经浏览了好几个小时,但我一生都无法弄清楚出了什么问题。我知道在将像素位置值转换为莫尔斯的代码部分发生了一些事情,但我看不出到底是什么问题。

如果有人可以帮助我指出哪里出了问题,以便我调整我的代码并从错误中吸取教训,希望我的技能得到提高,我将非常感激不尽。

【问题讨论】:

    标签: python python-3.x numpy python-2.7 python-imaging-library


    【解决方案1】:

    你计算:

    Y,X = np.where(np.all(im==white,axis=2))
    

    但你从不使用Y,只使用X,所以你实际上忽略了每个像素所在的行。如果一个像素位于Y行X列,你应该像这样分配它的位置:

    offset = (Y * imageWidth) + X
    

    【讨论】:

      【解决方案2】:

      如果我正确理解你想要做什么,那就是找到图像中每个白色像素的偏移量,然后计算它们之间的差异。

      这可以简洁地使用 np.diffprepend 参数来完成。请注意,要计算偏移量,您需要将y 乘以图像的宽度。

      import numpy as np
      
      def decode_message(image):
          _, width, _ = im.shape
          y, x = np.where(np.all(image == 255, axis=2))
          offsets_from_start = width * y + x
          differences = np.diff(offsets_from_start, prepend=[0])
          return ''.join(chr(d) for d in differences)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-23
        • 2015-10-28
        • 1970-01-01
        • 1970-01-01
        • 2022-06-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多