英文:
OpenCV, editing an image list directly leads to inaccuracies
问题
我正在学习使用Python的OpenCV,并尝试编辑图像中的一部分像素。
import cv2
img1 = cv2.imread('Assets/chess.jpg', 1)
for row in range(20, 50):
for column in range(20, 50):
img1[row][column] = [255, 0, 0]
cv2.imwrite('Assets/new_chess.jpg', img1)
在这段代码中,我将所有的像素都设置为[255, 0, 0],应该是蓝色。
然而,我得到的结果是这样的:
[我得到一个蓝色但带有较暗边框的正方形](https://i.stack.imgur.com/hO8wU.png)
当我回去打印正方形**角**上的像素的BGR值时,我得到的是[155 12 15]。
打印中间像素给我[255 0 7]。
我不明白为什么值不是像我设置的[255, 0, 0]。
英文:
I was learning OpenCV with python, and tried to edit a section of pixels in an image.
import cv2
img1 = cv2.imread('Assets/chess.jpg', 1)
for row in range(20, 50):
for column in range(20, 50):
img1[row][column] = [255, 0, 0]
cv2.imwrite('Assets/new_chess.jpg', img1)
In the code I am setting all the pixels to [255, 0, 0] which should just be blue.
However, what I get is this:
I get a square that is blue but with a darker border
When I went back and printed the BGR value of a pixel on the corner of the square I got [155 12 15].
Printing a pixel in the middle gave me [255 0 7].
I don't understand why the values aren't [255, 0, 0] like I set them to be.
答案1
得分: 0
你正在将图像保存为 .jpg
格式,这是一种有损压缩算法。
简而言之,每当保存 .jpg
图像时,该算法将图像转换为一堆正弦波,并剪切掉几个正弦波以减小文件大小(因此是一种压缩算法)。这就是为什么输入文件和输出文件不一致。
此外,由于算法规范的原因,你往往会注意到物体边缘发生显著变化,因为描述边缘的正弦波很可能会被消除,而恒定部分受到较小影响。你可以看到中间的值没有变化太多,但靠近边缘的像素发生了变化。
如@stateMachine建议的,你应该使用无损压缩算法来保存图像,例如 .png
,以便不丢失这些细节(当然输出文件的大小会更大)。
如果你感兴趣,Computerphile的这个视频可以帮助你更好地理解 JPEG(.jpg
)压缩算法:
https://www.youtube.com/watch?v=n_uNPbdenRs
英文:
You are saving the image as .jpg
format, which is a lossy compression algorithm.
In short, whenever a .jpg
image is saved, the algorithm transforms the image into a bunch of sine waves, and cut out several sine waves to reduce the file size (thus, a compression algorithm). That's why the input file and the output file is not consistent.
Furthermore, you tend to notice significant changes on the edge of objects because sine waves describing edges are most likely to be eliminated due to the algorithm specification, while the constant part are less affected. You can see the value in the middle did not change too much, but pixels near the edge did.
As suggested by @stateMachine, you should save the image with a lossless compression algorithm, .png
for example, in order not to loose these details. (the size of output file will be larger, of course).
If you are curious, great explanation of JPEG (.jpg
) compression algorithm from Computerphile would help:
https://www.youtube.com/watch?v=n_uNPbdenRs
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论