python - python中的按位和图像分辨率计算。有人可以解释代码吗?
问题描述
with open("image.jpg",'rb') as file:
file.seek(163)
a = file.read(2)
height = (a[0] << 8) - a[1]
a = file.read(2)
width = (a[0] << 8) - a[1]
print(str(height) + " x " + str(width))
我还在学习python。我知道按位运算符左移和右移。但我不明白这段代码。
我的理解是:
- 我们将二进制读取的图像作为文件打开。
- 用 将光标移动到 163
file.seek()
。为什么是163? - 读取大小为 2 个字节的文件。为什么?
我根本不明白第 4 行和第 6 行。打印功能还可以。
我尝试使用 Pillow 和 cv2。但万一我不能使用这些模块,我想我应该知道这个。
解决方案
这是粗略和丑陋但SOF0
包含图像高度和宽度的阅读,请参阅本文末尾附近。其实也是不对的。它应该是:
with open("image.jpg",'rb') as file:
file.seek(163)
a = file.read(2)
height = (a[0] << 8) | a[1] # It should be ORed in not subtracted
print(height)
a = file.read(2)
width = (a[0] << 8) | a[1] # It should be ORed in not subtracted
print(width)
另请参阅有关 JPEG 的Wikipedia条目。
作为一个小例子,让我们用ImageMagick制作一个 640x480 的红色 JPEG :
magick -size 640x480 xc:red image.jpg
现在让我们寻找SOF0
标记FF C0
:
xxd -c16 -g1 -u image.jpg | grep -A2 "FF C0"
00000090: 10 10 10 10 10 10 10 10 10 10 10 10 10 10 FF C0 ................
000000a0: 00 11 08 01 E0 02 80 03 01 11 00 02 11 01 03 11 ................
000000b0: 01 FF C4 00 15 00 01 01 00 00 00 00 00 00 00 00 ................
如果我们检查 640 和 480 在十六进制中的样子:
printf "%x %x" 480 640
1e0 280
你可以在文件的偏移量 163 处看到它们,因为偏移量a0
是 160,而我们是从那开始的 3 个字节。
推荐阅读
- python - 如何使第二个画布窗口可滚动?
- wordpress - 如何将带有 www 的子域重定向到主域?
- dependency-injection - .Net 核心 DI 范围验证,范围与瞬态?
- magento2 - 将附加数据添加到块(magento 2)
- java - 如何在 Delphi 代码中捕获 java 异常
- python - 如何将自动计数器添加到模型对象?
- android - 这种布局叫什么?
- django - 在哪里托管 wagtail/django
- java - Spring Boot 找不到 EmbeddedKafkaBroker Bean
- regex - 正则表达式按日期过滤我的日志