我的图像是315x581。我想从左上角到右下角在28x28中裁剪它,然后我需要将每个28x28图像保存在文件夹中。 我只能裁剪一个图像,从y1 = 0到y2 = 28,x1 = 0到x2 = 28.
第一个问题是:我使用了cv2.imwrite(" cropped.jpg",cropped)来保存这个小图像,但它没有保存它,只要它在上面的某些行上运行。
第二个问题是:如何编写一个代码,它保持从28到28左右从上到下裁剪图像并保存每个子图像。 我用过循环,但我不知道如何完成它。 非常感谢您的帮助。
这是我的代码,
import cv2
import numpy as np
from PIL import Image
import PIL.Image
import os
import gzip
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.cm as cm
#%%
image1LL='C:/Users/Tala/Documents/PythonProjects/Poster-OpenCV-MaskXray/CHNCXR_0001_0_LL.jpg'
mask1LL='C:/Users/Tala/Documents/PythonProjects/Poster-OpenCV-MaskXray/CHNCXR_0001_0_threshLL.jpg'
#finalsSave='C:/Users/Tala/Documents/PythonProjects/Poster-OpenCV-MaskXray/Xray Result'
# load the image
img = cv2.imread(image1LL,0)
mask = cv2.imread(mask1LL,0)
# combine foreground+background
final1LL = cv2.bitwise_and(img,img,mask = mask)
cv2.imshow('final1LL',final1LL)
cv2.waitKey(100)
final1LL.size
final1LL.shape
# Save the image
cv2.imwrite('final1LL.jpg',final1LL)
# crop the image using array slices -- it's a NumPy array
# after all!
y1=0
x1=0
for y2 in range(0,580,28):
for x2 in range(0,314,28):
cropped = final1LL[0:28, 0:28]
cv2.imshow('cropped', cropped)
cv2.waitKey(100)
cv2.imwrite("cropped.jpg", cropped)

答案 0 :(得分:0)
您的方法很好,但需要进行一些微调。以下代码将为您提供帮助:
import cv2
filename = 'p1.jpg'
img = cv2.imread(filename, 1)
interval = 100
stride = 100
count = 0
print img.shape
for i in range(0, img.shape[0], interval):
for j in range(0, img.shape[1], interval):
print j
cropped_img = img[j:j + stride, i:i + stride] #--- Notice this part where you have to add the stride as well ---
count += 1
cv2.imwrite('cropped_image_' + str(count) + '_.jpg', cropped_img) #--- Also take note of how you would save all the cropped images by incrementing the count variable ---
cv2.waitKey()
原始图片:
裁剪图片1
裁剪图片2
裁剪图片3
答案 1 :(得分:0)
如果您在PyTorch中将其用作深度学习框架,则此任务将非常容易,并且无需其他任何外部图像处理库(如OpenCV)即可完成。以下代码将以PyTorch张量的形式将单个图像转换为多个图像的堆栈。如果只想使用图像,则需要删除行“ transforms.ToTensor()”,然后使用matplotlib将代码中的“ tens”变量另存为图像。
注意:这里使用的鸟图像尺寸为32 x 32 x 3,裁剪图像的图像尺寸为5x5x3,步幅= 1。
image = Image.open('bird.png')
tensreal = trans(image)
trans = transforms.Compose([transforms.Resize(32),
transforms.ToTensor(),
])
stride = 1
crop_height = 5
crop_width = 5
img_height = 32
img_width = 32
tens_list = []
for i in range(0,img_width-crop_width,stride):
for j in range(0,img_height-crop_height ,stride):
tens = trans(image)
tens1 = tens[:, j:j+crop_height, i:i+crop_width]
tens_list.append(tens1)
all_tens = torch.stack(tens_list)
print(all_tens.size())